C++、C#、java演算法學習日記02----選擇排序(SelectSort)
直接選擇排序屬於排序演算法的一種,他的排序速度要比冒泡排序快一些,算是對冒泡排序的一種改進。
基本思想:
直接排序的思想類似於我們實際生活中的排序行為,比如:對一串數字 63,4,24,1,3,15從小到大排序,我們會首先找到最大的值與最後一位交換位置,然後再從餘下的數中找到最大的值與倒數第二位交換位置,這樣每次都從餘下的數中找到最大的放到末尾,當餘下一個數時排序完成
C++執行個體:
#includeusing namespace std;void ShowArray(int *array,int Length);void SelectSort(int *array,int Length){ for(int i=1;iarray[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
C#執行個體: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); } }}
以上結果都樣:
java執行個體: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;iarray[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();}}
結果: