I'm trying to take a file and run it through a sorting algorithm, insertion sort in this case. After I pass it through the algorithm and print the array, it doesn't look sorted. My thinking is because I'm trying to pass an array to the function, and view the information through a pointer, but I think I'm messing it up.
void insertionSort(int arr[]) {
int key, j;
for(int i = 1; i < (sizeof(arr) / sizeof(int)); i++) {
int key = arr[i];
int j = i-1;
while(j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j = j - 1;
}
arr[j+1] = key;
}
}
I have the function set to void because I thought I'd be able to just access the array since it is a pointer. Would it be better if I returned the array? My logic is obviously wrong, so any pointers (no pun intended) would be great.
Here is the block of code from my main()
case 2:
printf("Filling array...\n");
fp = fopen("Random.txt", "r");
if (fp == NULL) {
printf("\nError opening Random.txt\n");
exit(1);
}
for (int i = 0; i < (sizeof(arr) / sizeof(int)); i++) {
fscanf(fp, "%d", &arr[i]);
}
insertionSort(arr);
for (int i = 0; i < (sizeof(arr) / sizeof(int)); i++) {
printf("%d\n", arr[i]);
}
fclose(fp);
break;
}
void insertionSort(int arr[]) {is exactly the same asvoid insertionSort(int *arr) {(yes it's a pointer even when you write []). Hint 2: what'ssizeof(int*)/sizeof(int)?sizeof(arr)in theinsertionSortroutine will besizeof(int*)which is 8 byte, so what you are actually doing is8 / 4, which is 2sizeofto iterate through the entire array. I'm under the impression that I can't use.length()for example because C is not OOP? @0.sh Read above comment. Usingsizeofto iterate through array. If there's a better method, I'm open to it.sizeof(arr) / sizeof(int) = 2on x86_64 and1on x86.arr(in the function) isn't an array.