-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursiveQuickSort.qs
More file actions
45 lines (37 loc) · 1.37 KB
/
RecursiveQuickSort.qs
File metadata and controls
45 lines (37 loc) · 1.37 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
namespace Quantum.QuickSort {
open Microsoft.Quantum.Arrays;
operation QuickSort(input : Qubit[]) : Unit {
// Apply the QuickSort algorithm to the input array
ApplyQuickSort(input, 0, Length(input) - 1);
}
operation ApplyQuickSort(input : Qubit[], low : Int, high : Int) : Unit {
if (low < high) {
// Partition the input array
let pivotIdx = Partition(input, low, high);
// Apply QuickSort recursively to the sub-lists
ApplyQuickSort(input, low, pivotIdx - 1);
ApplyQuickSort(input, pivotIdx + 1, high);
}
}
operation Partition(input : Qubit[], low : Int, high : Int) : Int {
// Choose the pivot element (here we choose the last element)
let pivotValue = M(input[high]);
mutable i = low - 1;
for idx in low .. high - 1 {
if (M(input[idx]) < pivotValue) {
i = i + 1;
// Swap input[i] and input[idx]
SWAP(input, i, idx);
}
}
// Swap input[i + 1] and input[high] (the pivot)
SWAP(input, i + 1, high);
// Return the index of the pivot after partitioning
return i + 1;
}
operation SWAP(input : Qubit[], i : Int, j : Int) : Unit is Adj {
if (i != j) {
(input[i], input[j]) = (input[j], input[i]);
}
}
}