I’m facing problems running my C code for the problem TSORT.
Whenever I run the code given below it shows SIGSEGV error. I am unable to understand why I am facing this error.
#include <stdio.h>
void swap(int a, int b){
a = a + b;
b = a - b;
a = a - b;
}
int partition(int arr[], int low, int high){
int i, j;
i = low - 1;
for (j = low; j < high; j++){
if (arr[j] < arr[high]){
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quicksort(int arr[], int low, int high){
int pivot;
pivot = partition(arr, low, high);
quicksort(arr, low, pivot-1);
quicksort(arr, pivot+1, high);
}
main(){
int n, i;
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
quicksort(arr[n], 0, n-1);
for (i = 0; i < n; i++){
printf("%d\n", arr[i]);
}
}
Honking great compiler error when compiling with C++, which has stricter type-safety than C:
rishab_04-TSORT.cpp: In function ‘int main()’:
rishab_04-TSORT.cpp:37:20: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
quicksort(arr[n], 0, n-1);
~~~~~^
Edit:
Also, your swap is a no-op.
Edit2:
Also - quicksort - which is called recursively - doesn’t seem to have a base case/ stop condition.
Thank you for the reply, just a few concerns here:
I don’t understand why would there be any type conversion when I’m passing an integer array to a function which is supposed to accept integer arrays.
That swap code was something I used extensively in integer swaps while practising Java, so I just used it here without much thought. Is it a bad programming practice?
arr[n] is an integer, not an integer array (and you’re also making an out-of-bounds access).
Writing a swap function that doesn’t actually do anything is “a bad programming practice”, yes
Have you actually tried it?
#include <stdio.h>
void swap(int a, int b){
a = a + b;
b = a - b;
a = a - b;
}
int main(){
int x = 3, y = 4;
swap(x,y);
printf("x: %d y: %d\n", x, y);
}