We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Descending order code
Page Index Toggle Pages: 1
Descending order code (Read 246 times)
Descending order code
Dec 5th, 2008, 6:58pm
 
Hi all,

Im totally new to processing. We have been asked to write a couple of things for my University module but I have missed some pretty major things so am trying to catch up! First things first. I have managed to get the point where I have written a code for loading a .txt file with a string of numbers in, and now I need to sort them in descending order (highest first), but I have got it to work in Asending order instead! The code for this is below:

Nums = new int[Size];
 for (i = 0; i < Size; i++) {    
   Nums[i] = int(NumStrs[i]);    
 }
 for (i = 1; i < Size; i++) {
   Next = Nums[i];
   for (j = i - 1; (j >= 0) && (Nums[j] > Next); j--) {
     Nums[j + 1] = Nums[j];
   }
   Nums[j + 1] = Next;
 }
 PrintArray(Nums, 20, 20);  
}

How do I change this to make it work the other way?
Cheers
Tom
Re: Descending order code
Reply #1 - Dec 5th, 2008, 10:56pm
 
hey bud.

i looked at your code and i'm not sure how it is doing any sorting since there is no conditional logic (if statements) in there.

here is a simple sort you can do once you have your numbers in an array.  it's called a selection sort and it works like this: you run through all the items starting at the first one and find the biggest (or smallest) one.  now move that entry to the front of the list.  now run through the list again starting at the 2nd position and find the next biggest one and put it in the 2nd position.  continue doing this until you went through all the items in the list.

here is the code:

Code:

int[] numbers = {-10,8,7,-2,4,11,4};
int biggest;

//selection sort
for(int i = 0; i < numbers.length; i++) {
biggest = i;//set the biggest to the first of the remaining numbers

//find the biggest of the remaining numbers
for(int x = i + 1; x < numbers.length; x++) {
if (numbers[x] > numbers[biggest]) {
biggest = x;
}
}

//swap the biggest number found with the first position on the list of the remaining numbers
int temp=numbers[i];
numbers[i] = numbers[biggest];
numbers[biggest] = temp;
}

//print the results
for(int i=0; i < numbers.length; i++)
print(numbers[i] + " ");



you can find more on sorting algorithms here:
http://en.wikipedia.org/wiki/Sorting_algorithm
Page Index Toggle Pages: 1