C ++, C #, java Algorithm learning diary 02 ---- SelectSort)
Directly selecting sorting is one of the sorting algorithms. Its sorting speed is faster than that of Bubble sorting, which is an improvement of Bubble sorting.
Basic Idea:
The idea of direct sorting is similar to the sorting behavior in our real life, for example, sorting a string of numbers 63,4, 24,1, 3,15 from small to large, first, we will find the maximum value and the last position for switching, and then find the maximum value and the last second position for switching from the remaining number, in this way, the maximum value is found from the remaining number to the end, and the sorting is completed when the remaining number is reached.
C ++ instance:
# Include
Using namespace std; void ShowArray (int * array, int Length); void SelectSort (int * array, int Length) {for (int I = 1; I
Array [index]) {index = j ;}// put the maximum value at the end of int temp; temp = array [index]; array [index] = array [Length-I]; array [Length-I] = temp;} ShowArray (array, Length);} // output function void ShowArray (int * array, int Length) {for (int I = 0; I
C # example:
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); } }}
The preceding results are as follows:
Java instance:
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();}}
Result: