# Sorting an int array highest to lowest

• 07-27-2008
switchback
Sorting an int array highest to lowest
The goal is to have the user input the amount of numbers they want sorted, then the numbers themself. This part works fine.
The sorting idea is to take the largest value, move it to the last value in the array, and then repeat for the rest of the array.
The problem is the function to sort the numbers, for example, the input and output I get from running this program: (the print of the numbers back was just to test that it was recieveing them correctly)
Enter amount of numbers to be sorted: 4
Enter numbers to sort: 8 7 2 9
8729
In sorted order: -4261520 0 -4261576 -13354412

Not exactly sure why it's doing this and what's causing it.
Any pointers would be much appreciated.

Code:

```#include <stdio.h> void selection_sort(int a[], int low, int high); int split(int a[], int low, int high); int main(void) {   int i, n;   printf("Enter amount of numbers to be sorted: ");   scanf("%d", &n);   int a[n], b[n];   printf("Enter numbers to sort: ");   for (i = 0; i < n; i++) {     scanf("%d", &a[i]);   }   selection_sort(a, 0, n - 1);   printf("In sorted order: ");   for (i = 0; i < n; i++)     printf("%d ", b[i]);   printf("\n");   return 0; } void selection_sort(int a[], int low, int high) {   int i, max, temp1;   if (low == high) return;   for(i = 0; i < high; i++){     if (a[i] > max) {       max = a[i];       temp1 = a[high - 1];       a[i] = temp1;       a[high - 1] = max;     }   }   selection_sort(a, 0, high - 1); }```
• 07-27-2008
switchback
Figured it out, didn't remove the b[] from an earlier idea.
• 07-27-2008
switchback
Sorting won't work correctly now, turning off the recursion, all it does is take the last value in the array and move it to the first, regaurdless of if it's larger or not. The wrong direction of the sort, and making searching for the largest worthless.
Examples:
Enter amount of numbers to be sorted: 3
Enter numbers to sort: 1 2 3
In sorted order: 3 1 2
Enter amount of numbers to be sorted: 4
Enter numbers to sort: 1 2 3 4
In sorted order: 4 1 2 3
• 07-27-2008
anon
It seems that in your selection sort algorithm max is uninitialized initially.

It also seems to me that selection sort shouldn't assign values every iteration. The idea should be that you find the index with the maximum value (in the remaining range) and swap that with the first item (in the remaining range) once per outer loop (you could replace recursion with outer loop).

For example, this is how a sorting progress might look (swapped items at each iteration are bold, sorted range is green, unsorted red):
Code:

```Initial array: 8 7 9 2 1 8 Max element: array[2] = 9 After iteration #1:  9 7 8 2 1 8 Max element: array[2] = 8 After iteration #2:  9 8 7 2 1 8 Max element: array[5] = 8 After iteration #3:  9 8 8 2 1 7 Max element: array[5] = 7 After iteration #4:  9 8 8 7 1 2 Max element: array[5] = 2 After iteration #5:  9 8 8 7 2 1```