快速排序非递归版本 c
时间: 2024-06-03 20:05:46 浏览: 15
以下是快速排序的非递归版本C代码实现。[^1]
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 1000
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void quicksort(int arr[], int start, int end) {
if (start >= end) {
return;
}
int stack[MAX_STACK_SIZE], top = -1;
stack[++top] = start;
stack[++top] = end;
while (top >= 0) {
end = stack[top--];
start = stack[top--];
int pivot = arr[end];
int i = start - 1;
for (int j = start; j <= end - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[end]);
int p = i + 1;
if (p - 1 > start) {
stack[++top] = start;
stack[++top] = p - 1;
}
if (p + 1 < end) {
stack[++top] = p + 1;
stack[++top] = end;
}
}
}
int main() {
int arr[] = {7, 3, 1, 5, 2, 8, 4, 6};
int n = sizeof(arr) / sizeof(arr);
quicksort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)