算法--快排lomuto方法

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、思路

在这里插入图片描述
pivot是最终枢轴(4),partition是临时枢轴,始终指向第一个比pivot大的元素(7),变量i指向比pivot小的元素(1),当a[i]比pivot小时,交换i和partition(临时的枢轴元素),当a[i]比pivot大时,不用管,就是一趟遍历找到找到比pivot小的元素和临时枢轴partition交换;然后最终将临时枢轴partition和最终枢轴pivot交换即可

  • 1.定义pivot等于a[high]
  • 2.遍历数组,如果a[i]比pivot小,则交换a[i]和partition
  • 3.交换partition和high

二、代码

1.引入库

#include <stdio.h>
#include "io_utils.h"
#include <stdlib.h>
#include <time.h>

#define PLAYER_COUNT 50

void SwapElements(int array[], int first, int second) {
  int temp = array[first];
  array[first] = array[second];
  array[second] = temp;
}

void ShuffleArray(int array[], int length) {
  srand(time(NULL));
  //[0, RAND_MAX]
  for (int i = length - 1; i > 0; --i) {
    int random_number = rand() % i;
    SwapElements(array, i, random_number);
  }
}

int Partition(int array[], int low, int high) {
  int pivot = array[high];
  int partition = low;
  for (int i = low; i < high; ++i) {
    if (array[i] < pivot) {
      SwapElements(array, i, partition++);
    }
  }
  SwapElements(array, partition, high);

  return partition;
}

void QuickSort(int array[], int low, int high) {
  if (low >= high) return;
  int partition = Partition(array, low, high);
  QuickSort(array, low, partition - 1);
  QuickSort(array, partition + 1, high);
}


int main() {
  int players[PLAYER_COUNT];
  for (int i = 0; i < 50; ++i) {
    players[i] = i;
  }
  // players : 0, 1, ..., 49
  PRINT_INT_ARRAY(players, PLAYER_COUNT);
  ShuffleArray(players, PLAYER_COUNT);
  PRINT_INT_ARRAY(players, PLAYER_COUNT);

  QuickSort(players, 0, PLAYER_COUNT - 1);

  PRINT_INT_ARRAY(players, PLAYER_COUNT);

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值