10个排序算法,待更新
2021/5/13 20:26:53
本文主要是介绍10个排序算法,待更新,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.冒泡和快速排序
/// <summary> /// bubble sort /// </summary> /// <param name="arr">the array to sort</param> /// <returns></returns> public int[] BubbleSort(int[] arr) { Console.WriteLine($"Origin: { String.Join(",", arr)}"); int step = 0; for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length-i-1; j++) { var leftItem = arr[j]; var rightItem = arr[j+1]; if (leftItem > rightItem) { arr[j] = rightItem; arr[j + 1] = leftItem; string currentArrString = GetArrItemString(arr); Console.WriteLine($"Step{++step} {leftItem} <=>{rightItem} : {currentArrString}"); } } } return arr; } /// <summary> /// Get the array string /// </summary> /// <param name="arr">the array to be converted to string</param> /// <returns></returns> private string GetArrItemString(int[] arr) { StringBuilder resultStr = new StringBuilder(); if (arr.Length == 0) { return String.Empty; } for (int i = 0; i < arr.Length; i++) { resultStr.Append(arr[i].ToString()); resultStr.Append(","); } return resultStr.ToString(); } /// <summary> /// Swap two positions' value /// </summary> /// <param name="arr">The array</param> /// <param name="left">left array index</param> /// <param name="right">right array index</param> private void Swap(int[] arr, int left, int right) { var templateValue = arr[left]; arr[left] = arr[right]; arr[right] = templateValue; string currentArrString = GetArrItemString(arr); Console.WriteLine($"Step {arr[left]} <=>{arr[right]} : {currentArrString} index: {left} <=> {right} "); } /// <summary> /// Quick scan /// </summary> /// <param name="arr">The array to sort</param> public void QuickSort(int[] arr, int left, int right) { if (left > right) { return; } var temp = arr[left]; int i = left, j = right; while (i < j) { while ( i < j && arr[j] >= temp) { j--; }; while (i < j && arr[i] <= temp) { i++; } if ( i < j) { Swap(arr, i, j); } } //arr[left] = arr[i]; //arr[i] = temp; Swap(arr, left, i); string currentArrString = GetArrItemString(arr); Console.WriteLine($"Current Array : {currentArrString}, i = {i}"); QuickSort(arr, left, i-1); QuickSort(arr, i+1, right); }
2.待更新
这篇关于10个排序算法,待更新的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略