I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k ) {
for(int i = 0; i < size; i ) {
if(array[i] > array[i 1]){
int temp = array[i];
array[i] = array[i 1];
array[i 1] = temp;
}
}
}
}
CodePudding user response:
You are not looping correctly. Looks like you are trying bubble sort
which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k )
for(int i = k 1; i < size; i )
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
CodePudding user response:
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i )
{
for(int j=0;j<size-1-i;j )
{
if(array[j]>array[j 1])
{
swap(array[j] , array[j 1]);
}
}
}
}
I see that you are trying to implement the bubble sort
algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j
and the element next to it at index j 1
. If array[j]
is greater than array[j 1]
, you swap them using the swap()
function or by using the temp
method. The outer loop will run size - 1
times , and the inner loop will run size - 1 - i
times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i
. You can see the nested loop runs less number of times in each iteration of the outer loop.
CodePudding user response:
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1
, therefore i 1
is equal to size
, thus data[i 1]
is out of range. Simply change the condition of your for
to be i < size - 1
.
Working example: https://godbolt.org/z/e5ohWPfTz