C++、C#、java演算法學習日記02----選擇排序(SelectSort)

來源:互聯網
上載者:User

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();}}

 

結果:

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.