Skip to content

Commit daca1ac

Browse files
authored
Add files via upload
1 parent a6c23fb commit daca1ac

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Dart/Quicksort.dart

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
void main() {
2+
List<int> list = [7, 2, 1, 8, 6, 3, 5, 4];
3+
int high = list.length - 1;
4+
int low = 0;
5+
List<int> result = quickSort(list, low, high);
6+
print(result);
7+
}
8+
9+
List<int> quickSort(List list, int low, int high) {
10+
if (low < high) {
11+
int pi = partition(list, low, high);
12+
print("pivot: ${list[pi]} now at index $pi");
13+
14+
quickSort(list, low, pi - 1);
15+
quickSort(list, pi + 1, high);
16+
}
17+
return list;
18+
}
19+
20+
int partition(List<int> list, low, high) {
21+
// Base check
22+
if (list.isEmpty) {
23+
return 0;
24+
}
25+
// Take our last element as pivot and counter i one less than low
26+
int pivot = list[high];
27+
28+
int i = low - 1;
29+
for (int j = low; j < high; j++) {
30+
// When j is < than pivot element we increment i and swap arr[i] and arr[j]
31+
if (list[j] < pivot) {
32+
i++;
33+
swap(list, i, j);
34+
}
35+
}
36+
// Swap the last element and place in front of the i'th element
37+
swap(list, i + 1, high);
38+
return i + 1;
39+
}
40+
41+
// Swapping using a temp variable
42+
void swap(List list, int i, int j) {
43+
int temp = list[i];
44+
list[i] = list[j];
45+
list[j] = temp;
46+
}

0 commit comments

Comments
 (0)