java
public class QuickSort {
public static void main(String[] args) {
int[] nums = {2, 4, 1, 0, 3, 5};
QuickSort test = new QuickSort();
test.quickSort(nums, 0, nums.length - 1);
for (int num : nums) {
System.out.println(num + " ");
}
}
public static void swap1(int a, int b) {
int temp = a;
a = b;
b = temp;
}
public void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public int partition(int[] nums, int left, int right) {
int i = left;
int j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--;
while (i < j && nums[i] <= nums[left])
i++;
swap(nums, i, j);
}
swap(nums, i, left);
return i;
}
public void quickSort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int pivot = partition(nums, left, right);
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
}
go
type QuickSort struct {
}
func (q *QuickSort) partition(nums []int, left, right int) int {
i, j := left, right
for i < j {
for i < j && (nums[j] >= nums[left]) {
j--
}
for i < j && (nums[i] <= nums[left]) {
i++
}
nums[i], nums[j] = nums[j], nums[i]
}
nums[i], nums[left] = nums[left], nums[i]
return i
}
func (q *QuickSort) quickSort(nums []int, left, right int) {
if left >= right {
return
}
pivot := q.partition(nums, left, right)
q.quickSort(nums, left, pivot-1)
q.quickSort(nums, pivot+1, right)
}
c++
#include <iostream>
#include <vector>
using namespace std;
class QuickSort {
public:
void swap(vector<int> &nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
int partition(vector<int> &nums, int left, int right) {
int i = left;
int j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left]) {
j--;
}
while (i < j && nums[i] <= nums[left]) {
i++;
}
swap(nums, i, j);
}
swap(nums, i, left);
return i;
}
void quickSort(vector<int> &nums, int left, int right) {
if (left >= right) {
return;
}
int pivot = partition(nums, left, right);
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
};
int main() {
QuickSort test;
vector<int> nums = {2, 1, 3, 5, 6, 4};
test.quickSort(nums, 0, nums.size() - 1);
for (const auto &item: nums) {
cout << item << " ";
}
}