Problem
I have a source code in Java for sorting array elements using the merge sort
algorithm. The principle uses a loop to compare an element in the array with the element in the next index in the array. If the earlier is bigger than the later then the numbers are swapped logically to reassign
the array elements in the indices.
My problem is that the Java algo works but the C algo does not. The logic is the same, what am I doing wrong....
Code
Working Java Code
static void sort(int[] arr){
for(int i=0;i<arr.length;i ){
for(int j=i 1;j<arr.length;j ){
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
C Code built on the same merge sort pseudocode as the Java Source code but fails to work
void sorting(int d[])
{
for (int i = 0; i < sizeof(d); i )
{
for (int j = i 1; j < sizeof(d); j )
{
if (d[i] > d[j])
{
int temp = d[i];
d[i] = d[j];
d[j] = temp;
}
}
}
}
Input Format
Both methods got parameters from arrays initialized to a fixed size and then a loop was used to get input from user and asign to the array, the user has to enter the size of the array first.
Reliability of the merge sort algo in other languages
I have applied the mergesort pseudocode in JavaScript, Python and C# and they all worked. I do not know why C would be an exception, please help...
CodePudding user response:
In general you should use std::array
or std::vector
instead of raw arrays (int[]
). They also offer more functions that you might know from Java or other languages. Also checkout std::swap
.
#include <iostream>
#include <vector>
void sorting(std::vector<int>& d)
{
for (int i = 0; i < d.size(); i )
{
for (int j = i 1; j < d.size(); j )
{
if (d[i] > d[j])
{
std::swap(d[i], d[j]);
/*
int temp = d[i];
d[i] = d[j];
d[j] = temp;
*/
}
}
}
}
int main()
{
std::vector<int> test = {5,1,4,3,2};
sorting(test);
for( auto const& elem : test )
{
std::cout << elem << " ";
}
std::cout << "\n";
return EXIT_SUCCESS;
}
CodePudding user response:
For starters there is no merge sort algorithm in your question.
In fact there is a modified insertion sort algorithm.
This function declaration
void sorting(int d[])
is adjusted by the compiler to the declaration
void sorting(int *d)
That is the parameter has a pointer type.
So the expression
sizeof(d)
yields the size of a pointer not the number of element in the passed array.
You need also to pass to the function the number of elements in the array.
The function can look the following way
void sorting( int a[], size_t n )
{
for ( size_t i = 0; i < n; i )
{
size_t min = i;
for ( size_t j = i 1; j < n; j )
{
if ( a[j] < a[min] ) min = j;
}
if ( i != min ) std::swap( a[i], a[min] );
}
}
Another approach is using a template function that accepts an array by reference.
For example
template <size_t N>
void sorting( int ( &a )[N] )
{
for ( size_t i = 0; i < N; i )
{
size_t min = i;
for ( size_t j = i 1; j < N; j )
{
if ( a[j] < a[min] ) min = j;
}
if ( i != min ) std::swap( a[i], a[min] );
}
}