Reputation: 21
So I've just started learning about C and algorithms and I've came across a problem in my selection sort algorithm. It gives me this as the output:
>10
>12
>13
>16
>23
>25
>42
>60
>50
>52
The last three digits are out of order. Looking from my eyes they shouldn't be. Can you tell me guys what can be the problem here? Also my goal is to do this without any pointers and such, it's still a bit blurry from the last lecture and I know it can be done without it. I believe that this is more of a logical than memory error. Thank you everyone!
#include <stdio.h>
int main(void) {
int max = 10;
int a[max];
//Makes unsorted array
a[0] = 10;
a[1] = 23;
a[2] = 50;
a[3] = 12;
a[4] = 52;
a[5] = 60;
a[6] = 25;
a[7] = 13;
a[8] = 42;
a[9] = 16;
/*
SWAP MODEL
printf("a[2] = %d \n", a[2]);
int temp = a[3];
a[3] = a[2];
a[2] = temp;
printf("a[2] = %d \n", a[2]);
*/
//Sorts array
int n;
int s = 0;
int p = 0;
for (n = 0; n < max-1; n++){
int smallest = a[n];
for(s = n + 1; s < max; s++){
if(smallest > a[s]) {
smallest = a[s];
p = s;
}
}
if (n == 0 && p == 0) {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else if (n > 0 && p == 0) {
p = n;
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
}
//Checks if sorted
for(int number = 0; number < 10; number++) {
printf("%d \n", a[number]);
}
}
Upvotes: 2
Views: 89
Reputation: 95328
int smallest = a[n];
Here you forget to initialize p = n
, so your invariant smallest == a[p]
is violated. With that addition it works.
Some more comments:
if (n == 0 && p == 0) {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else if (n > 0 && p == 0) {
p = n;
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
This whole construct is redundant, it just does the same thing in every case. You can replace it by an unconditional swap. My attempt at a cleaned up version:
for (int n = 0; n < max-1; n++){
int p = n;
int smallest = a[p];
for (int s = n + 1; s < max; s++){
if (smallest > a[s]) {
smallest = a[s];
p = s;
}
}
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
Upvotes: 3