Home > Java > javaTutorial > body text

Code examples for selection sorting in Java

黄舟
Release: 2017-08-11 09:40:34
Original
2521 people have browsed it

This article mainly introduces Java simple selection sorting examples in detail, which has certain reference value. Interested friends can refer to it

1. Basic concepts

In each pass, the record with the smallest keyword is selected from the records to be sorted, and the order is placed at the end of the sorted record sequence until all sorting is completed.

2. Implementation ideas

From the sequence to be sorted, find the element with the smallest keyword;
If the smallest element is not the first element of the sequence to be sorted , exchange it with the first element;
From the remaining N - 1 elements, find the element with the smallest keyword, and repeat steps (1) and (2) until the sorting is completed.

3. Code implementation


public class SelectionSort {

 public static void selectionSort(int[] list){
  //需要遍历获得最小值的次数
  if (1>=list.length)return;
  for (int i=0;i<list.length-1;i++){
   int temp=0;
   int index=i;  //选择当前值为最小值索引
   for (int j=i+1;j<list.length;j++){
    if (list[index]>list[j]){
     index=j; //修改最小值索引
    }
   }
   
   temp=list[index];
   list[index]=list[i];
   list[i]=temp;
  }
 }
 public static void main(String[] args){
  int[] list={4,3,6,5,7,8,2,10,2,9};
  selectionSort(list);
  for (int num:list){
   System.out.print(num+" ");
  }
 }
}
Copy after login

4. Time complexity

The number of comparisons for simple selection sorting has nothing to do with the initial sorting of the sequence. Assuming that the sequence to be sorted has N elements, the number of comparisons is always N (N - 1) / 2.

The number of moves is related to the initial sorting of the sequence. When the sequence is in positive order, the number of moves is the least, which is 0.

When the sequence is in reverse order, the number of moves is the most, which is 3N (N - 1) / 2.

So, based on the above, the time complexity of simple sorting is O(N2).

The above is the detailed content of Code examples for selection sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template