C - Quick Sort (one of the simplest)

向右看齐 2022-10-23 15:26 246阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * Quick Sort:
  3. *
  4. * Given an array, one element is chosen and the others partitioned in two subsets
  5. * - those less than the partition element and those greater than or equal to it.
  6. * The same process is then applied recursively to the two subsets. When a subset
  7. * has fewer than two elements, it doesn't need any sorting; this stops the recursion.
  8. *
  9. * This version of quicksort is not the fastest possible, but it's one of the simplest.
  10. * We use the middle element of each subarray for partitioning.
  11. *
  12. * QuickSort.c - by FreeMan
  13. */
  14. /* QuickSort: Sort v[left]...v[right] into increasing order */
  15. void QuickSort(int v[], int left, int right)
  16. {
  17. int i, last;
  18. void Swap(int v[], int i, int j);
  19. if (left >= right) /* Do nothing if array contains fewer than two elements */
  20. {
  21. return;
  22. }
  23. Swap(v, left, (left + right) >> 1); /* Move partition element to v[left] */
  24. last = left;
  25. for (i = left + 1; i <= right; i++) /* Partition */
  26. {
  27. if (v[i] < v[left])
  28. {
  29. Swap(v, ++last, i);
  30. }
  31. }
  32. Swap(v, left, last); /* Restore partition element */
  33. QuickSort(v, left, last - 1);
  34. QuickSort(v, last + 1, right);
  35. }
  36. /* Swap: Interchange v[i] and v[j] */
  37. void Swap(int v[], int i, int j)
  38. {
  39. int temp;
  40. temp = v[i];
  41. v[i] = v[j];
  42. v[j] = temp;
  43. }

发表评论

表情:
评论列表 (有 0 条评论,246人围观)

还没有评论,来说两句吧...

相关阅读

    相关 quick_sort

    于冒泡排序是以相邻元素来比较和交换的,因此,若一个元素离其最终位置较远,则需要进行多次的比较和移动操作。而快速排序则很好的解决了上述问题。 所以,可以说快排是冒泡排序的...

    相关 快速排序(Quick Sort)

    一、算法原理 设要排序的数组是A\[0\]……A\[N-1\],首先任意选取一个数据(通常选用数组的第一个数)作为关键 数据,然后将所有比它小的数据放到它前面,所有比它大

    相关 快速排序(Quick Sort)

    快速排序可以理解为:快速排序=挖坑填数+分治算法; 快速排序(Quick Sort)使用分治法(Divide and conquer)策略来把一个序列分为两个子序列,左右两个

    相关 快速排序(Quick-Sort)

    快速排序的主要思想是根据一个基准数(一般是待排序集中第一个元素)将一个待排序集分成左右两部分,其中左半部分数据集比右半部分数据集均要小或大,接下来,对左和右半部分按照相同的方法

    相关 快速排序(quick sort)

    快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序n个项目要Ο(n log n)次比较。在最坏状况下则需要Ο(n2)次比较,但这种状况并不常见。事实上,快速排序通常