直接选择排序属于排序算法的一种,他的排序速度要比冒泡排序快一些,算是对冒泡排序的一种改进。
直接排序的思想类似于我们实际生活中的排序行为,比如:对一串数字 63,4,24,1,3,15从小到大排序,我们会首先找到最大的值与最后一位交换位置,然后再从余下的数中找到最大的值与倒数第二位交换位置,这样每次都从余下的数中找到最大的放到末尾,当余下一个数时排序完成
#include<iostream> using namespace std; void ShowArray(int *array,int Length); void SelectSort(int *array,int Length) { for(int i=1;i<Length;i++) //控制循环趟数 { int index=0; //循环找到最大值 for(int j=1;j<=Length-i;j++) { if(array[j]>array[index]) { index=j; } } //将最大值放到末尾 int temp; temp=array[index]; array[index]=array[Length-i]; array[Length-i]=temp; } ShowArray(array,Length); } //输出函数 void ShowArray(int *array,int Length) { for(int i=0;i<Length;i++) { cout<<array[i] <<" "; } cout<<endl; } void main() { int array[]={63,4,24,1,3,15}; int Length=sizeof(array)/sizeof(array[0]); //获取数组长度 SelectSort(array,Length); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SelectSort { class Sort { public void SelectSort(int[] array) { for (int i = 1; i < array.Length; i++) { int index = 0; for (int j = 1; j <= array.Length - i; j++) { if (array[j] > array[index]) { index = j; } } int temp; temp = array[index]; array[index] = array[array.Length - i]; array[array.Length - i] = temp; } ShowArray(array); } public void ShowArray(int[] array) { foreach (int i in array) { Console.Write(i + " "); } Console.WriteLine(); } static void Main(string[] args) { Sort sorter = new Sort(); int[] array = new int[] {63,4,24,1,3,15}; sorter.SelectSort(array); } } }
以上结果都样:
package Sort; public class SelectSort { public static void main(String[] args) { int[] array ={63,4,24,1,3,15}; SelectSort sorter = new SelectSort(); sorter.sort(array); } public void sort(int[] array){ int index; for(int i=1;i<array.length;i++){ index=0; for(int j=1;j<=array.length-i;j++){ if(array[j]>array[index]){ index=j; } } int temp = array[array.length-i]; array[array.length-i]=array[index]; array[index]=temp; } showArray(array); } public void showArray(int[] array){ for(int i:array){ System.out.print(" "+i); } System.out.println(); } }
结果:
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++、C#、java算法学习日记02----选择排序(SelectSort)
原文:http://blog.csdn.net/hc666/article/details/49490945