void sort(int values[], int n)
{
int smallestSpot = 0;
for (long long i = 0; i < n ; i++)
{
int smallest = values[i];
for(long long j = i; j < n - i ; j++) //find the smallest int in array
{
if(values[j] < smallest)
{
smallestSpot = j;
smallest = values[j];
}
}
values[smallestSpot] = values[i];
values[i] = smallest;
}
return;
}
My sorting algorithm overwrites what the first number is, and I can't find out why, please help. Thanks.
Thanks for COLDSPEED and GAURANG VYAS by perform that changes we reachs to working version of code.
#include <stdio.h>
void sort(int values[], int n){
int smallestSpot = 0;
for (long long i = 0; i < n ; i++){
int smallest = values[i];
smallestSpot = i;
for(long long j = i+1; j < n ; j++){ //find the smallest int in array
if(values[j] < smallest){
smallestSpot = j;
smallest = values[j];
}
}
values[smallestSpot] = values[i];
values[i] = smallest;
}
}
int main(void){
int arr[5] = {8,1,9,10,2};
sort(arr,5);
for(int i=0;i<5;i++){
printf("%d\n",arr[i]);
}
return 0;
}
Before try to coding on computer, trace your algorithm with pen and paper.
We have many sorting algorithms.
I suggest to see this link and gain a visual understanding about sorting problems and way of solving them.
Edit