Subject: How to get least value numbers in a sorted array?
Posted By: ashokparchuri Post Date: 1/31/2006 11:30:11 AM
Hi,

   I had a doubt that if we have an sorted array with some numbers like 45,54,65,34,34,23,78. How can we get the least umbers in this arrray?
Please reply me as soon as possible.

Thanks-Ashok
Reply By: liamfitz Reply Date: 6/24/2006 9:25:38 AM
Ashok, it will depend on your language very much, but in principle, you would code for a 'bubble sort', which means you look at each elememt in the array in turn and compare it to the other elements. Storing the lower number in a variable on each comparison, until eventually the smallest number is stored in the variable. Post again with more detail, I write in Visual Basic.liamfitz.

Reply By: jlh42581 Reply Date: 12/1/2006 2:17:57 PM
in javascript/perl/php slight difference in declaration of variables but i will do it in js. Per suggested previously.

var lowest_num=0;
for(var i=0;i<array_name.length;i++){
 if(array_name.length != i){ // no need to look at last
  var temp_holder = array_name[i];
  var temp_holder2 = arrau_name[i+1] // look one ahead
  if(temp_holder < temp_holder2){
    lowest_num=temp_holder;
  }
  else{
   lowest_num=temp_holder2;
  }
 }
}

should be fairly close, if not working

now if you wanna build a numerically sorted array, i suggest you look at "push / pop" method

Reply By: ciderpunx Reply Date: 12/5/2006 8:25:46 AM
Most languages have built in sorting, which works well in the majority of cases - you should use these. If keeping the information in a sorted order is important you may want to consider using a data structure other than an array.

Anyhow, here's a couple of snippets that find the lowest number in an array.

Here's a perl version:

my @unsorted = (34, 69, 12, 67, 21, 9, 78, 478327);
my @sorted = sort {$a <=> $b} @unsorted;
print "$sorted[0]\n";


Here's a ruby version:

arr=[34, 69, 12, 67, 21, 9, 78, 478327]
p arr.sort.first


Cheers

--
Don't Stand on your head - you'll get footprints in your hair
                                           http://charlieharvey.org.uk
                                              http://charlieharvey.com

Go to topic 52793

Return to index page 102
Return to index page 101
Return to index page 100
Return to index page 99
Return to index page 98
Return to index page 97
Return to index page 96
Return to index page 95
Return to index page 94
Return to index page 93