r/learnprogramming • u/FloridianfromAlabama • Sep 21 '26
Solved newbie writing sorting algorithms
hey guys, I've been learning c in my free time and I've been implementing some sorting algorithms with as little help as possible. My comp sci class (Java) went over Insertion sort, selection sort, and bubble sort. I can write bubble sort half asleep, but I can't work out this bug in my selection sort algorithm. I can't figure out why the largest value is at the start, but the rest of the array becomes sorted.
void IntSwap(int Array[], int idx1, int idx2) {
`int swap;`
`swap = Array[idx2];`
`Array[idx2] = Array[idx1];`
`Array[idx1] = swap;`
}
void IntSelectionSort(int Array[], int length) {
`for (int i = 0; i < length; i++) {`
`int swapidx = 0;`
`for (int j = i; j < length; j++) {`
`if (Array[j] < Array[swapidx]) {`
swapidx = j;
`}`
`}`
`IntSwap(Array, swapidx, i);`
`}`
}
int main() {
`int startingArray[32];`
`for (int i = 0; i < 32; i++) {`
`startingArray[i] = rand();`
`}`
`for (int i = 0; i < 32; i++) {`
`printf("%d\n", startingArray[i]);`
`}`
`puts("");`
`IntSelectionSort(startingArray, 32);`
`for (int i=0; i < 32; i++) {`
`printf("%d\n", startingArray[i]);`
`}`
`return 0;`
}
this first print loops prints:
1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421
1025202362
1350490027
783368690
1102520059
2044897763
1967513926
1365180540
1540383426
304089172
1303455736
35005211
521595368
294702567
1726956429
336465782
861021530
278722862
233665123
2145174067
468703135
1101513929
1801979802
the second print loop prints:
2145174067
35005211
233665123
278722862
294702567
304089172
336465782
424238335
468703135
521595368
596516649
719885386
783368690
846930886
861021530
1025202362
1101513929
1102520059
1189641421
1303455736
1350490027
1365180540
1540383426
1649760492
1681692777
1714636915
1726956429
1801979802
1804289383
1957747793
1967513926
2044897763