快速排序示例

package Sort;

//快速排序示例

public class KuiSuSort {

	public static void printArray(int[] a) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + "  ");
		}
		System.out.println("");
	}

	public static void sort(int a[], int low, int high) {

		if (low >= high) {
			return;
		}

		int temp = a[low];
		int rlow = low;
		int rhigh = high;
		int tag = 0;//标志位,0移动high指针,1移动low指针

/*		while (high > low) {
			if (tag == 0) {
				while (high>low) {
					if (a[high] < temp) {
						a[low] = a[high];
						low++;
						break;
					} else {
						high--;
					}
				}
				tag = 1;
			} else {
				while (high>low) {
					if (a[low] > temp) {
						a[high] = a[low];
						high--;
						break;
					} else {
						low++;
					}
				}
				tag = 0;
			}

		}*/
		while (high > low) {
			if (tag == 0) {	
					if (a[high] < temp) {
						a[low] = a[high];
						low++;
						tag = 1;
					} else {
						high--;
					}
			} else {
					if (a[low] > temp) {
						a[high] = a[low];
						high--;
						tag = 0;
					} else {
						low++;
					}
				}	
		}
		
		//System.out.println(low + "  " + high);
		a[low] = temp;

		sort(a, rlow, low - 1);

		sort(a, low + 1, rhigh);

	}

	public static void main(String[] args) {
		int[] a = { 38, 65, 97, 76, 13, 27, 49, 2, 78, 75, 56, 48, 89, 10, 3,
				852 };
		printArray(a);

		KuiSuSort.sort(a, 0, a.length - 1);

		printArray(a);
	}

}

</pre><pre>


                
C++中的快速排序是一种常用的排序算法,它基于分治的思想。下面是一个示例代码: ```cpp #include <iostream> using namespace std; // 交换两个元素的值 void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } // 将数组分为两部分,并返回分割点的索引 int partition(int arr[], int low, int high) { int pivot = arr[high]; // 选取最后一个元素作为基准值 int i = (low - 1); // 记录小于基准值的元素的索引 for (int j = low; j <= high - 1; j++) { // 如果当前元素小于等于基准值,则将其放入左侧部分 if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); // 将基准值放入正确的位置 return (i + 1); } // 快速排序函数 void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); // 获取分割点的索引 // 对分割点左侧和右侧的子数组进行递归排序 quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // 打印数组 void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; } int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr); cout << "原始数组:"; printArray(arr, n); quickSort(arr, 0, n - 1); cout << "排序后的数组:"; printArray(arr, n); return 0; } ``` 这段代码实现了快速排序算法。首先定义了一个`swap`函数用于交换两个元素的值。然后定义了`partition`函数,它选择最后一个元素作为基准值,将数组分为两部分,并返回分割点的索引。接下来是`quickSort`函数,它使用递归的方式对分割点左侧和右侧的子数组进行排序。最后,在`main`函数中定义了一个示例数组,并调用`quickSort`函数进行排序,然后打印排序后的数组。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值