forked from moogacs/problem-solving
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.c
More file actions
81 lines (72 loc) · 1.38 KB
/
Copy pathquick_sort.c
File metadata and controls
81 lines (72 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* This algorithm uses the quicksort algorithm
* to sort an array of n elements
* best case: O(n log n)
* worst case: O(n^2)
* average case: O(n log n)
*/
/* I/O
* Numero di elementi: 5 (This is the number of elements)
* Inserisci 5 numeri: 4 1 3 0 100
* 0 1 3 4 100 (This is the new sorted array)
*/
#include <stdlib.h>
#include <stdio.h>
#define MAX 300
void scambia(int *, int*);
int leggi_array(int []);
void QuickSort(int [], int, int);
void stampa_array(int [], int);
int main(void) {
int n, V[MAX];
n = leggi_array(V);
QuickSort(V, 0, n-1);
stampa_array(V, n);
return(0);
}
//Interchange numbers
void scambia(int *x, int *y) {
int z;
z = *x;
*x = *y;
*y = z;
return;
}
//get input and number of elements
int leggi_array(int V[]) {
int n, i;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("Inserisci %d numeri: ", n);
for (i=0; i<n; i++)
scanf("%d", &V[i]);
return(n);
}
//print array
void stampa_array(int V[], int n) {
int i;
for (i=0; i<n; i++) {
printf("%d ", V[i]);
}
printf("\n");
return;
}
void QuickSort(int V[], int low, int high)
{
int pivot = V[high];
int t = 0;
if(low < high)
{
for(int i=0;i<high;i++)
{
if(V[i]<pivot)
{
scambia(&V[i], &V[t]);
t++;
}
}
scambia(&V[t], &V[high]);
QuickSort(V, low, t-1);
QuickSort(V, t+1, high);
}
}