Created
October 15, 2019 22:20
-
-
Save katsaii/057745dd88b766efb5efc75615949b9e to your computer and use it in GitHub Desktop.
Sorts an array and removes any duplicate elements.
This file contains 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> | |
void swap(int* a, int i, int j) { | |
int temp = a[i]; | |
a[i] = a[j]; | |
a[j] = temp; | |
return; | |
} | |
int partition(int* a, int left, int right) { | |
int pivot = left; | |
++left; | |
while (left <= right) { | |
if (a[left] <= a[pivot]) { | |
swap(a, left, pivot); | |
++left; | |
++pivot; | |
} else { | |
swap(a, left, right); | |
--right; | |
} | |
} | |
return pivot; | |
} | |
void quicksort(int* a, int start, int end) { | |
if (start < end) { | |
int pivot = partition(a, start, end); | |
quicksort(a, start, pivot - 1); | |
quicksort(a, pivot + 1, end); | |
} | |
} | |
void compress(int* a, int* size) { | |
int i, j; | |
for (i = 1; i < *size; ++i) { | |
int item = a[i - 1]; | |
for (j = i; j < *size; ++j) { | |
if (item == a[j]) { | |
--*size; | |
swap(a, j, *size); | |
} | |
} | |
} | |
} | |
int main() { | |
int size; | |
printf("Enter the number of elements: "); | |
scanf("%d", &size); | |
int* items = (int*) malloc(size); | |
printf("Enter the elements:\n"); | |
int i; | |
for (i = 0; i < size; ++i) { | |
printf(" [%d]: ", i); | |
scanf("%d", items + i); | |
} | |
quicksort(items, 0, size - 1); | |
compress(items, &size); | |
printf("Sorted:\n"); | |
for (i = 0; i < size; ++i) { | |
printf(" [%d]: %d\n", i, items[i]); | |
} | |
free(items); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment