I tried to sort a struct array with merge sort, but somehow it'll only work when the struct variable is only one. This is the simplified code that i made:
#include <stdio.h>
#include <string.h>
struct name{
int number;
};
void mergeSort(name arr[5], int left, int right){
if(left == right){
return;
}
int middle = (right - left) / 2 + left;
mergeSort(arr, left, middle);
mergeSort(arr, middle+1, right);
int leftIdx = left,
leftLimit = middle,
rightIdx = middle+1,
rightLimit = right,
tempIdx = 0;
name tempArr[right - left];
while(leftIdx <= leftLimit && rightIdx <= rightLimit){
if(arr[leftIdx].number < arr[rightIdx].number){
tempArr[tempIdx] = arr[leftIdx];
tempIdx++;
leftIdx++;
}else{
tempArr[tempIdx] = arr[rightIdx];
tempIdx++;
rightIdx++;
}
}
while(leftIdx <= leftLimit){
tempArr[tempIdx] = arr[leftIdx];
tempIdx++;
leftIdx++;
}
while(rightIdx <= rightLimit){
tempArr[tempIdx] = arr[rightIdx];
tempIdx++;
rightIdx++;
}
tempIdx = 0;
for(int i=left; i<=right; i++){
arr[i] = tempArr[tempIdx];
tempIdx++;
}
}
int main(){
name arr[5];
for(int i=0; i<5; i++){
scanf("%d", &arr[i].number);
}
mergeSort(arr, 0, 4);
for(int i=0; i<5; i++){
printf("%d", arr[i].number);
}
return 0;
}
The code above works as intended. But as soon as i add a different type of variable to the struct, ran the code, and input the scanf, i ran into an error (not returning 0). for example:
struct name{
int number;
char name[101];
};
Anyone got any clue why is this happening and how if i want to put more variables inside the struct? I'm genuinely so confused when i found out the reason why my code wasn't working (and i have no clue how to fix this).