Java sorting Algorithm (ii): Simple selection sorting

Source: Internet
Author: User

[Basic idea]

In the set of numbers to be sorted, select the smallest number to exchange with the first position, and then in the remaining number, find the smallest and second position of the number of exchanges, so loop to the penultimate number and the last number comparison.

Algorithm key: Find the smallest number, and use the variable to remember its subscript.


[Java Implementation]

public class Simpleselectionsort {public static void main (string[] args) {int[] arr = {9, 1, 5, 8, 3, 7, 4, 6, 2}; System.out.println ("Before sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}  Simple selection of sort simpleselectionsort (arr); System.out.println (); System.out.println ("After sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}}              /** * Simple selection sort */private static void Simpleselectionsort (int[] arr) {for (int i = 0; i < arr.length; i++) { int min = i; Defines the current subscript as the lowest value subscript for (int j = i + 1; j < Arr.length; J + +) {if (Arr[min] >                  ARR[J]) {//If there is a keyword less than the current minimum value, assign the subscript of this keyword to min min = j;              }} if (i! = min) {//If min is not equal to I, the description finds the minimum value, swap swap (arr, I, min);  }}}/** * Element exchange position */private static void swap (int[] arr, int i, int min) {int tmp = Arr[min];  Arr[min] = Arr[i]; Arr[i] = tmp;}}
[Algorithmic features]

Complexity of Time: O (n^2)

The most important feature of this algorithm is that the number of mobile data exchanged is very small, which saves the corresponding time. Analyzing its time complexity you will find that the number of comparisons is the same, regardless of the best and worst case scenario.

Simple selection of the performance of the sorting is better than the bubble sort.


Java sorting Algorithm (ii): Simple selection sorting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.