Created
November 29, 2021 21:01
-
-
Save giljr/1d1aa9e5240ab66de5fe5fb91c1c1845 to your computer and use it in GitHub Desktop.
Quick Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#define VECTORSIZE 10 | |
void quicksort(int vet[], int p, int u); | |
int partition(int vet[], int p, int u); | |
void swap(int vet[], int i, int j); | |
int main() | |
{ | |
int vet[VECTORSIZE] = { 0 }; | |
srand(time(NULL)); | |
for (int i = 0; i < VECTORSIZE; i++) | |
vet[i] = rand() % 100; | |
printf("QUICK SORT (Ascendant)\n"); | |
printf("NOT ORDERED VECTOR:\n"); | |
for (int i = 0; i < VECTORSIZE; i++) // Print NOT ORDERED VECTOR | |
printf("%d\t", vet[i]); | |
quicksort(vet, 0, VECTORSIZE - 1); | |
// Print resultants | |
printf("\nORDERED VECTOR:\n"); | |
for (int i = 0; i < VECTORSIZE; i++) // Print ORDERED VECTOR | |
printf("%d\t", vet[i]); | |
printf("\n"); | |
system("pause"); | |
return 0; | |
} | |
void quicksort(int vet[], int p, int u) | |
{ | |
int m; | |
if (p < u) | |
{ | |
m = partition(vet, p, u); | |
quicksort(vet, p, m); | |
quicksort(vet, m + 1, u); | |
} | |
} | |
int partition(int vet[], int p, int u) // Find pivot, scan and swap | |
{ | |
int pivo, pivo_pos, i, j; | |
pivo_pos = (p + u) / 2; | |
pivo = vet[pivo_pos]; | |
i = p - 1; | |
j = u + 1; | |
while (i < j) | |
{ | |
do // test the values on the right | |
{ | |
j--; | |
} while (vet[j] > pivo); | |
do // test the values on the left | |
{ | |
i++; | |
} while (vet[i] < pivo); | |
if (i < j) | |
swap(vet, i, j); | |
} | |
return j; | |
} | |
void swap(int vet[], int i, int j) | |
{ | |
int aux; | |
aux = vet[i]; | |
vet[i] = vet[j]; | |
vet[j] = aux; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment