-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQS.java
More file actions
102 lines (81 loc) · 2.32 KB
/
Copy pathQS.java
File metadata and controls
102 lines (81 loc) · 2.32 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//TO-DO
//Añadir contadores e impresores para calcular número de operaciones y tiempo.
//Crear gráficas
//Tras eso, modificar el algoritmo para que se detenga y haga subdivisiones
//Hacer una memoria de la práctica
import java.lang.Math;
import java.util.Arrays;
public class QS {
public final static int MAX_NUMBER = 10000000;
public final static int MAX_VECTOR = 10;
private static long numAsignaciones;
private static long numComparaciones;
public static void main(String args[]) {
int tam = Integer.parseInt(args[0]);
int numVect = (int) (Math.random() * MAX_VECTOR);
for (int n = 0; n < numVect; n++) {
int[] array = new int[tam];
numAsignaciones = 0;
numComparaciones = 0;
long tiempoInicio = System.currentTimeMillis();
for (int i = 0; i < tam; i++) {
array[i] = (int) (Math.random() * MAX_NUMBER);
}
quickSort(array, 0, tam - 1);
long tiempoFinal = System.currentTimeMillis();
/*for (int j = 0; j < tam; j++) {
System.out.println(array[j]);
}*/
System.out.println("Tiempo transcurrido: " + ((tiempoFinal - tiempoInicio)/1000)+" segundos");
System.out.println("Número de comparaciones: "+numComparaciones);
System.out.println("Número de asignaciones: "+numAsignaciones);
System.out.println("");
}
}
public static int pivote(int[] arr, int low, int high) {
int longitud = high - low;
int a = (int) (Math.random() * longitud) + low;
int b = (int) (Math.random() * longitud) + low;
int c = (int) (Math.random() * longitud) + low;
int array[] = new int[3];
array[0] = arr[a];
array[1] = arr[b];
array[2] = arr[c];
Arrays.sort(array);
return array[1];
}
public static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
int pivot = pivote(arr, low, high);
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
numComparaciones++;
i++;
}
numComparaciones++;
while (arr[j] > pivot) {
numComparaciones++;
j--;
}
numComparaciones++;
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
numAsignaciones += 3;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
}