Skip to content
Snippets Groups Projects
Verified Commit 80bc7568 authored by orestis.malaspin's avatar orestis.malaspin
Browse files

added quicksort

parent ccda03b3
No related branches found
No related tags found
No related merge requests found
Pipeline #35714 passed
#include <stdlib.h>
#include <stdio.h>
void print_tab(int size, int tab[size]) {
for (int i = 0; i < size; ++i) {
printf("%d ", tab[i]);
}
printf("\n");
}
void swap(int *lhs, int *rhs) {
int tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
int partition(int tab[], int ind_min, int ind_max) {
// ind_min == 0
// ind_max == 6
int pivot = tab[ind_max]; // 12
int i = ind_min - 1; // 0
int j = ind_max; // 6
while (i < j) {
do {
i += 1; // 0, tab[0] == 1 < 12
} while (tab[i] < pivot && i < j);
do {
j -= 1; // j == 5, tab[5] < 12
} while (tab[j] > pivot && i < j);
if (i < j) {
swap(&tab[i], &tab[j]);
}
}
swap(&tab[i], &tab[ind_max]);
return i;
}
void quicksort(int tab[], int ind_min, int ind_max) {
int size = ind_max - ind_min + 1;
if (size > 1) {
int ind_pivot = partition(tab, ind_min, ind_max);
if (ind_pivot - ind_min > 0) {
quicksort(tab, ind_min, ind_pivot - 1);
}
if (ind_max - ind_pivot > 0) {
quicksort(tab, ind_pivot + 1, ind_max);
}
}
}
int main(int argc, char *argv[]) {
int size = argc - 1;
int tab[size];
for (int i = 0; i < size; ++i) {
tab[i] = atoi(argv[i + 1]);
}
print_tab(size, tab);
quicksort(tab, 0, size - 1);
print_tab(size, tab);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment