Skip to content
On this page

quicksort.c


标签:代码片段C/algo  
c
#include <stdio.h>
#include <stdlib.h>

int one_time(int a[], int low, int high) {
  int key = a[low];
  while (low < high) {
    while (low < high && a[high] >= key)
      high--;
    a[low] = a[high];
    while (low < high && a[low] <= key)
      low++;
    a[high] = a[low];
  }
  /* 此时 low 等于 high */
  a[low] = key;
  return low;
}

void quick_sort(int a[], int low, int high) {
  if (low < high) {
    int mid = one_time(a, low, high);
    quick_sort(a, low, mid - 1);
    quick_sort(a, mid + 1, high);
  }
}

int main() {
  int a[] = {12, 135, 23, 234, 123,
			 0, 12, 8, 56, 1};
  int len = sizeof(a) / sizeof(a[0]);
  quick_sort(a, 0, len - 1);
  for (int i = 0; i < 10; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");
  return 0;
}

Last updated: