I'm trying to design a function quicksort in C which sorts a array of ints in a decendent way.
I'm trying this code: print_arr ista a function that prints all the elements of an array. swap changes to elements from an array partition changes the array so to have have the pivote in the between the upper elements and the lower elements, and it returns the position where the pivote is going to be. quicksort is the function which sorts the array. Main is the main function where I create the array to sort.
#include <stdlib.h>
#include <stdio.h>
void print_arr(int arr[], int lon) {
for (int i = 0; i < lon; i++) {
printf("%d ", arr[i]);
}
}
void swap(int *a, int *b) {
int *temp = a;
a = b;
b = temp;
}
int partition(int arr[], int low, int high) {
int pivote = arr[low];
int i = low + 1;
for (int j = i; j < high; j++) {
if (arr[j] < pivote) {
swap(&arr[i], &arr[j]);
i++;
}
}
return (i);
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
int main() {
int arr[5] = {3, 4, 1, 2, 5};
quicksort(arr, 0, 5);
print_arr(arr, 5);
puts("");
return 0;
}
So I expect an output like:
1 2 3 4 5
but I get:
3 4 1 2 5
void swap(int *a, int *b) {
int *temp = a;
a = b;
b = temp;
}
The above code merely exchanges pointers and leaves the pointed to data unchanged. It should be rewritten as:
void swap (int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}