C# 递归式快速排序算法
2024-10-07 01:43:40
static void Main(string[] args)
{ Console.WriteLine("************快速排序*****************");
int[] list = new int[] { , , , , , , , };
QuickSort qs = new QuickSort();
qs.quikSort(list, , list.Length - );
for (int i = ; i < list.Length; i++)
{
Console.WriteLine("第{0}位是{1}", i + , list[i]);
}
// Console.WriteLine(list); Console.ReadKey();
} //递归快速排序法
public class QuickSort
{
//快速排序
public void quikSort(int[] arr, int startIndex, int endIndex)
{
//递归结束条件 startIndex>endIndex
if (startIndex >= endIndex)
{
return;
} //得到基准元素的位置
int pivotIndex = partiton(arr, startIndex, endIndex); //根据基准元素,分成两部分递归排序
quikSort(arr, startIndex, pivotIndex - );
quikSort(arr, pivotIndex + , endIndex);
}
//指针交换法
private static int partiton(int[] arr, int startIndex, int endIndex)
{
//取第一个位置的元素作为基准元素
int pivot = arr[startIndex];
int left = startIndex;
int right = endIndex; while (left != right)
{
//控制right指针比较并左移
while (left < right && arr[right] > pivot)
{
right--;
} //控制right指针比较并右移
while (left < right && arr[left] <= pivot)
{
left++;
} //交换left和right指向的元素
if (left < right)
{
int p = arr[left];
arr[left] = arr[right];
arr[right] = p;
}
} //pivoe和指针重合点交换
int s = arr[left];
arr[left] = arr[startIndex];
arr[startIndex] = s; return left;
}
//挖坑法
private static int partiton1(int[] arr, int startIndex, int endIndex)
{
// 4, 7, 6, 5, 3, 2, 8, 1
//获取第一个位置的元素作为基准元素
int pivot = arr[startIndex]; //
int left =startIndex; //
int right = endIndex; //7 //坑的位置,初始等于pivot的位置
int index = startIndex; //0 //大循环在左右指针重合或交错时结束
while (right >= left)
{
//right指针从右向左进行比较
while (right >= left)
{
int a = arr[right];
if (arr[right] < pivot)
{
int s = arr[right];
int t = arr[left]; arr[left] = arr[right];
index = right;
left++;
break;
}
right--;
} //left指针从左向右进行比较
while (right > left)
{
if (arr[left] >= pivot)
{
int a = arr[right];
int b = arr[left]; arr[right] = arr[left];
index = left;
right--;
break;
}
left++; }
} arr[index] = pivot;
return index;
}
}
最新文章
- 值得收藏!国外最佳互联网安全博客TOP 30
- Tensorflow 官方版教程中文版
- [fiddler] 手机抓包
- 基于MATLAB求解矩阵的正交补矩阵
- 进程间通信--fork函数
- WCF 部署在Windows 2012 IIS上各种报错的解决方法
- FZU1894 单调队列
- 转 android launch flow
- 4.1HTML和Bootstrap css精华
- JavaWeb学习记录(十九)——jsp标签库
- lintcode:在二叉查找树中插入节点
- LogstashL reference 重要章节
- python学习第二天:数字与字符串转换及逻辑值
- Ubutn14.04下caffeine工具不显示在工具栏中的问题
- EOF
- JS获取登录者IP和登录城市
- centos7 安装 redis-4.0.9
- OpenFlow学习笔记
- Ubuntu下安装Kafka Manager
- cron笔记
热门文章
- spark streaming 6: BlockGenerator、RateLimiter
- mongodb aggregate 聚合 操作(扁平化flatten)
- Note 1 for <;Pratical Programming : An Introduction to Computer Science Using Python 3>;
- JScript 对字符串、数组处理的常用方法
- Python全栈开发第5天作业
- 自定义application的全局捕获异常实现
- [VBA]提取指定字符串后的数字--代码来源Excelhome
- Python排序搜索基本算法之归并排序实例分析
- iOS UItextView监听输入特定字符跳转页面选择选项返回
- Element Children