简体   繁体   English

Java - 选择排序算法

[英]Java - Selection Sort Algorithm

I have some questions about selection sort.I'm a little bit confused.我有一些关于选择排序的问题。我有点困惑。

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order 
        }
    }

Output is:输出是:

4
3
2
1
4
3
2
4
3
4

What's wrong?怎么了?

selection sort is about finding the min value in each step of loop.选择排序是关于在循环的每个步骤中找到最小值。 you didn't find out the min value (by if statement maybe), just simply exchange the value in your inner loop.您没有找到最小值(可能通过 if 语句),只是简单地交换内部循环中的值。 so you actually didn't do a sort.所以你实际上没有做排序。

correction based on your implementation:根据您的实施进行更正:

final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
    int min;
    for (int i = 0; i < arr.length; i++) {
        // Assume first element is min
        min = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min = j;

            }
        }
        if (min != i) {
            final int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        System.out.println(arr[i]);// I print the in ascending order
    }

this should give you output:这应该给你输出:

1
2
3
4
5

Correct:正确的:

public class Test {

public static void main(String args[]){
    int[] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;
        for(int j = i + 1;j<arr.length;j++)
        {
            if(arr[j] < arr[min]) { min = j;}
        }
        int temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
        System.out.println(arr[i]);//I print the in ascending order 
    }
}

}

About the min part: it just refers to the index of whatever is the current min.关于 min 部分:它只是指当前 min 的索引。 You move on down the array until you meet the new min, and set min to that index.您继续向下移动数组,直到遇到新的最小值,并将 min 设置为该索引。 So 5 is the minimum number [min =0] until you see 4 [so now min =1] but then you compare 3 to whatever is stored at 4 [when min=1] and then realize that you should set min=2.... etc. etc.所以 5 是最小数字 [min =0] 直到你看到 4 [所以现在 min =1] 但是你将 3 与存储在 4 [当 min = 1 时] 的任何内容进行比较,然后意识到你应该设置 min = 2。 ……等等等等。

Your question appears to be in your comment您的问题似乎在您的评论中

min = i;//Selection sort algorithm says that find the minimum in the
        // array, but first element is not minimum.What's point here?

The point of that is you can assume the first one you're checking is the lowest just so you have a place to start from.关键是你可以假设你检查的第一个是最低的,这样你就有一个开始的地方。 After all, it might not be the minimum over all, but of the one's you've checked in this iteration, it's the lowest so far!毕竟,它可能不是最低的,但在您在本次迭代中检查过的那些中,它是迄今为止最低的!

You should first find the minimum instead of assuming the first element is the minimum您应该首先找到最小值,而不是假设第一个元素是最小值

int[] array = {5, 4, 3, 2, 1};
for ( int i = 0; i < array.length; i++ ) {

  //find minimum, starting from index i
  int minIndex = i;
  int min = array[i];
  for ( int j = i + 1; j < array.length; j++ ) {
    if ( array[ j ] < min ) {
      minIndex = j;
      min = array[j];
    }
  }

  // now move the smallest element to the front, and the element at index i to the index of the minimal element
  int temp = array[ i ];
  array[ i ] = min;
  array[ minIndex ] = temp;
}
/* Implementation of selection sort */

import java.util.Arrays;
import java.util.Scanner;


public class SelectionSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of elements of the array");
        int n = in.nextInt();
        int []a = new int[n];
        System.out.println("Enter the integer array of elements");
        for (int i=0; i<n ; i++)
        {
            a[i] = in.nextInt();
        }
        System.out.println("Before Sorting: "+Arrays.toString(a));
        a = sort(a);
        System.out.println("After Sorting: "+Arrays.toString(a));
    }

    private static int[] sort(int[] a) {
        // TODO Auto-generated method stub

        for(int i=0; i<a.length-1;i++)
        {
            int index=i;
            for(int j=i+1; j<a.length;j++)

                if(a[j]<a[index])
                {
                    index=j;
                }
                int small = a[index];
                a[index] = a[i];
                a[i]=small;

        }
        return a;
    }
}

What is wrong is that in your inner loop you should update your index, using the strategy you follow of doing the swap in the inner loop I made a working selection sort:问题是在你的内部循环中你应该更新你的索引,使用你在内部循环中进行交换的策略我做了一个工作选择排序:

import java.util.Arrays;

public class SelectionSort {

  public static void main(String[] args) {
    int[] input = new int[] {5,2,4,6,1,3};
    System.out.println( Arrays.toString(selectionSort(input)) );
  }

  public static int[] selectionSort(int[] input) {
    int length = input.length;
    int minimumValue = Integer.MAX_VALUE;

    for (int i = 0; i < length; ++i) {
        // find the minimumValue when j > i and swap it  with input[i] location
        for (int j =i; j < length; ++j) {
          if (input[j] <= minimumValue ) {
            minimumValue = input[j];
            input[j] = input[i];
            input[i] = minimumValue;
          }
        }
        minimumValue = Integer.MAX_VALUE;
    }
    return input;
  }

}

I added to github .我添加到github

As mentioned earlier, you're not updating your 'min' variable in the inner loop.如前所述,您不会在内部循环中更新“min”变量。 The objective of the inner loop is to find the index of the smallest element.内部循环的目标是找到最小元素的索引。 You should also move the 'swap' to the outer loop.您还应该将“交换”移动到外循环。 Below is the Selection Sort pseudo code:下面是选择排序伪代码:

Selection Sort
Inputs:
  A: an array
  n: the number of elements in A to sort

Procedure SELECTION-SORT (A, n)
1. For i = 0 to n – 1:
  A. Set minIndex to i.
  B. For j = i + 1 to n:
    i. If A[j] < A[minIndex], then set minIndex to j. // Add this
  C. Swap A[i] with A[minIndex]. // Move this to outside of the inner loop

Take a look at the link to my blog below to see a full explanation of the Selection Sort algorithm.请查看下面我博客的链接,以查看选择排序算法的完整说明。 There are implementations in Java, C++, Python, and JavaScript.在 Java、C++、Python 和 JavaScript 中有实现。

http://brianredd.com/algorithm/selection-sort http://brianredd.com/algorithm/selection-sort

public class SelectionSort {

public static void main(String[] args) {
    int[] A = {5,4,3,2,1};
    int l = A.length;

    for (int i = 0; i < l-1; ++i ){
        int minPos = i;

        // Find the location of the minimal element
        for (int j = i + 1; j < l; ++j){
            if ( A[j] < A[minPos]){
                minPos = j;
            }
        }

        if (minPos != i){
            int temp = A[i];
            A[i] = A[minPos];   
            A[minPos] = temp;
        }
    }
    System.out.println(Arrays.toString(A));
}
}

Assume a lowest element, which requires scanning the all elements and then swap it to the first position.假设最低元素,需要扫描所有元素,然后将其交换到第一个位置。

private static void selectionSortMethod(int[] arr) {

        for (int i = 0; i < arr.length - 1; i++) {  //no of iterations for array length
            for (int j = i + 1; j < arr.length; j++) {  //starting from next index to lowest element(assuming 1st index as lowest)
                if (arr[i] > arr[j]){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }

        }
         //print 
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
    int[] arr = {5,4,3,2,1};

    for (int i = 0; i < arr.length - 1; i++)
         {
            int index = i;
              for (int j = i + 1; j < arr.length; j++)
                  if (arr[j] < arr[index]) 
                   index = j;

            int smallerNumber = arr[index];  
            arr[index] = arr[i];
            arr[i] = smallerNumber;
      }

This is the correct method for selection sort The thing you have been doing wrong is you are swapping within the inner loop but actually the swapping needs to be done after the first complete round of inner loop where the minimum element is determined.这是选择排序的正确方法您一直做错的事情是您在内部循环中进行交换,但实际上交换需要在确定最小元素的第一轮完整内部循环之后完成。

public class Selectionsort{公共类选择排序{

public static int arr[];公共静态 int arr[]; public static int y;公共静态int y;

public static void main( String args[] ){公共静态无效主要(字符串参数[]){

System.out.println("Enter number of element you want to enter for sorting"); System.out.println("输入要排序的元素个数");

int nofele= Integer.parseInt(args[0]);

System.out.println("Enter number of element entered for sorting is "+ "\n" +nofele);

arr = new int[nofele];

System.out.println("Entered array is");

for(int i=1,j=0;i<=nofele;i++,j++){

arr[j]=Integer.parseInt(args[i]);

  System.out.println(arr[j]);

}

System.out.println("Sorted array for selection sort is ");

for(int k=0;k<nofele-1;k++)  {





  for(int l=nofele-k,b=1;l>=2;l--,b++){

    if(arr[k]>arr[k+b]){



     int temp=arr[k];

      arr[k]=arr[k+b];

      arr[k+b] = temp;


    }     

  }

   System.out.println(arr[k]);

}

   System.out.println(arr[nofele-1]);

} }

} }

Selection sort is a algorithm that forming array elements in ANSI order or DENSI order.选择排序是一种以 ANSI 顺序或 DENSI 顺序形成数组元​​素的算法。 Best case, Average case and Worst case time complexity is (n 2 ).最佳情况、平均情况和最坏情况时间复杂度为 (n 2 )。 Selection sort is not better for sorting an array... Selection sort implementation is given below:选择排序并不适合对数组进行排序...选择排序实现如下:

import java.util.Scanner;

class selection{
      public static void main(String a[]){

             Scanner sc=new Scanner(System.in);
             System.out.print("size :");
             int n=sc.nextInt();

             int i,j,tmp,minVal;

             int[] ar=new int[n];

             for(i=0;i<n;i++){
                  ar[i]=sc.nextInt();
             }

             for(i=0;i<(n-1);i++){
                  minVal=ar[i];
                  for(j=(i+1);j<n;j++){
                          if(minVal>ar[j]){
                                  minVal=ar[j];
                                  tmp=ar[i];
                                  ar[i]=minVal;
                                  ar[j]=tmp;
                          }
                  }

            }

            for(i=0;i<n;i++){
                  System.out.print(ar[i]+"  ");
            }
  }

pass the unsorted array get the sorted array传递未排序的数组得到排序的数组

 public int[] selectionSort(int[] list) {
            int i, j, minValue, minIndex, temp = 0;
            for (i = 1; i < list.length; i++) {
                minValue = list[i];
                minIndex = i;
                j = i - 1;
                for (j = i; j < list.length; j++) {

                    if (list[j] < minValue) {
                        minValue = list[j];
                        minIndex = j;
                    }

                }
                if (list[i] > minValue) {
                    temp = list[i];
                    list[i] = list[minIndex];
                    list[minIndex] = temp;
                }

            }
            return list;
        }

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.选择排序算法通过从未排序的部分重复找到最小元素(考虑升序)并将其放在开头来对数组进行排序。 The algorithm maintains two subarrays in a given array.该算法在给定数组中维护两个子数组。

1) The subarray which is already sorted. 1) 已经排序的子数组。 2) Remaining subarray which is unsorted. 2) 未排序的剩余子数组。

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.在选择排序的每次迭代中,未排序的子数组中的最小元素(考虑升序)被挑选出来并移动到已排序的子数组中。

Example:例子:

arr[] = 64 25 12 22 11

// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64

// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64

// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64 

Java Code is: Java代码是:

void sort(int arr[]) 
    { 
        int n = arr.length; 

        // One by one move boundary of unsorted subarray 
        for (int i = 0; i < n-1; i++) 
        { 
            // Find the minimum element in unsorted array 
            int min_idx = i; 
            for (int j = i+1; j < n; j++) 
                if (arr[j] < arr[min_idx]) 
                    min_idx = j; 

            // Swap the found minimum element with the first 
            // element 
            int temp = arr[min_idx]; 
            arr[min_idx] = arr[i]; 
            arr[i] = temp; 
        } 
    } 

And Be Clear that Arrays are Passed by Reference!并且要清楚数组是通过引用传递的!

Just pass array and size of array只需传递数组和数组大小

private void selectionSort() {
    for (int i = 0; i < arraySize; i++) {
        for (int j = i; j < arraySize; j++) {
            if (array[i] > array[j])
                swapValues(i,j);
        }
    }
}
private void swapValues(int posOne, int posTwo) {
    int tValue = array[posOne];
    array[posOne] = array[posTwo];
    array[posTwo] = tValue;
}

Algorithm of selection sort.选择排序算法。

  1. In the given array, get the 0th index as the minimum value.在给定的数组中,获取第 0 个索引作为最小值。
  2. Next consider the remaining array to figure out whether any element is less than the given 0th index, then swap.接下来考虑剩余的数组以确定是否有任何元素小于给定的第 0 个索引,然后交换。
  3. process this same step for the next index 1st to nth, automatically it will get sorted.对下一个索引第 1 到第 n 处理相同的步骤,它会自动排序。

The sample program as follows示例程序如下

class Sort{
    private void selectionSort(Integer[] elements) {
        for(int i=0;i<elements.length;i++) {
            int minIndex = i;
            for(int j=i+1;j<elements.length;j++) {
                if(elements[minIndex]>elements[j]) {
                    minIndex = j;
                }
            }
            int temp = elements[i];
            elements[i] = elements[minIndex];
            elements[minIndex] = temp;
        }
    }
    public static void main(String arsgs[]) {
        Integer[] elements = {5,4,3,2,1};
        new Sort().selectionSort(elements);
        Arrays.asList(elements).stream().forEach(System.out::println);
    }
}
                        import java.util.*;
        public class Sorting{
            public static void main(String[]args){
                long startTime;
                long selectionTime;
                long bubbleTime;
                long insertionTime;
                long parallelTime;
                long quickTime;
                int[]copy = shuffle();
                int[]copy1 = Arrays.copyOf(copy,100000);
                int[]copy2 = Arrays.copyOf(copy,100000);
                int[]copy3 = Arrays.copyOf(copy,100000);
                int[]copy4 = Arrays.copyOf(copy,100000);
                int[]copyD = descending();
                int[]copy5 = Arrays.copyOf(copyD,100000);
                int[]copy6 = Arrays.copyOf(copyD,100000);
                int[]copy7 = Arrays.copyOf(copyD,100000);
                int[]copy8 = Arrays.copyOf(copyD,100000);
                System.out.println("************** SORT RESULTS (millis) **************" + "\n" + "\n");
                System.out.print("[Bubble]");
                startTime = System.currentTimeMillis();
                bubbleSort(ascending());
                bubbleTime = System.currentTimeMillis() - startTime;
                System.out.print("    Ascending:    " + bubbleTime + "       ");
                startTime = System.currentTimeMillis();
                bubbleSort(copyD);
                bubbleTime = System.currentTimeMillis() - startTime;
                System.out.print("    Descending:    " + bubbleTime + "       ");
                startTime = System.currentTimeMillis();
                bubbleSort(copy);
                bubbleTime = System.currentTimeMillis() - startTime;
                System.out.print("    Shuffled:    " + bubbleTime + "       ");
                System.out.println("\n");
                System.out.print("[Selection]");
                startTime = System.currentTimeMillis();
                selectionSort(ascending());
                selectionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Ascending:    " + selectionTime + "       ");
                startTime = System.currentTimeMillis();
                selectionSort(copy5);
                selectionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Descending:    " + selectionTime + "       ");
                startTime = System.currentTimeMillis();
                selectionSort(copy1);
                selectionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Shuffled:    " + selectionTime + "       ");
                System.out.println("\n");
                System.out.print("[Quick]");
                startTime = System.currentTimeMillis();
                quick(ascending());
                quickTime = System.currentTimeMillis() - startTime;
                System.out.print("    Ascending:    " + quickTime + "       ");
                startTime = System.currentTimeMillis();
                quick(copy6);
                quickTime = System.currentTimeMillis() - startTime;
                System.out.print("    Descending:    " + quickTime + "       ");
                startTime = System.currentTimeMillis();
                quick(copy2);
                quickTime = System.currentTimeMillis() - startTime;
                System.out.print("    Shuffled:    " + quickTime + "       ");
                System.out.println("\n");
                System.out.print("[Parallel]");
                startTime = System.currentTimeMillis();
                parallel(ascending());
                parallelTime = System.currentTimeMillis() - startTime;
                System.out.print("    Ascending:    " + parallelTime + "       ");
                startTime = System.currentTimeMillis();
                parallel(copy7);
                parallelTime = System.currentTimeMillis() - startTime;
                System.out.print("    Descending:    " + parallelTime + "       ");
                startTime = System.currentTimeMillis();
                parallel(copy3);
                parallelTime = System.currentTimeMillis() - startTime;
                System.out.print("    Shuffled:    " + parallelTime + "       ");
                System.out.println("\n");
                System.out.print("[Insertion]");
                startTime = System.currentTimeMillis();
                insertionSort(ascending());
                insertionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Ascending:    " + insertionTime + "       ");
                startTime = System.currentTimeMillis();
                insertionSort(copy8);
                insertionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Descending:    " + insertionTime + "       ");
                startTime = System.currentTimeMillis();
                insertionSort(copy4);
                insertionTime = System.currentTimeMillis() - startTime;
                System.out.print("    Shuffled:    " + insertionTime + "       ");
                System.out.println("\n");
                
            }
            public static void selectionSort(int[] list)
            {
                for(int top = list.length - 1; top > 0; top--){
                    int largeLoc = 0;
                    for(int i = 1; i <= top; i++){
                        if(list[i] > list[largeLoc]){
                            largeLoc = i;
                        }
                    }
                    int temp = list[top];
                    list[top] = list[largeLoc];
                    list[largeLoc] = temp;
                }
            }
            public static void bubbleSort(int[]list){
                boolean swap = false;
                do{
                    swap = false;
                    for(int i=0;i<list.length-1;i++){
                        if(list[i] > list[i+1]){
                            int temp = list[i];
                            list[i] = list[i+1];
                            list[i+1] = temp;
                            swap = true;
                        }
                    }
                }while(swap != false);
            }
            public static void insertionSort(int[]list){
                for(int i=0;i<list.length;i++){
                    int c = list[i];
                    int j = i - 1;
                    while(j >= 0 && list[j] > c){
                        list[j + 1] = list[j];
                        j--;
                        list[j + 1] = c;
                    }
                }
            }
            public static void parallel(int[]list){
                Arrays.parallelSort(list);
            }
            public static void quick(int[]list){
                Arrays.sort(list);
            }
            public static int[] shuffle(){
                int[] shuffleArray = new int[100000];
                for(int i=0;i<100000;i++){
                    int rand=(int)(Math.random()*100000) + 1;
                    shuffleArray[i] = rand;
                }
                return shuffleArray;
            }
            public static int[] descending(){
                int[]descendingArray=new int[100000];
                int c=0;
                for(int i=100000;i>=1;i--){
                    descendingArray[c] = i;
                    c++;
                }
                return descendingArray;
            }
            public static int[] ascending(){
                int c1=0;
                int[]ascendingArray=new int[100000];
                for(int i=1;i<=100000;i++){     
                    ascendingArray[c1] = i;
                    c1++;
                }
                return ascendingArray;
            }
        }

You should start by assuming that the first element is the smallest one, then iterate over the array and if you find a smaller element, remember that position and assume that is the smallest one.您应该首先假设第一个元素是最小的元素,然后遍历数组,如果找到较小的元素,请记住该位置并假设它是最小的元素。 When you get to the end of the array you should know the position of the smallest value.当您到达数组的末尾时,您应该知道最小值的位置。 Switch that value with the value at the first position.将该值与第一个位置的值切换。 Now the smallest value is first.现在最小值是第一个。 Start at next position, assume that is the smallest value, iterate over the rest of the array... (I think you get the idea.从下一个位置开始,假设它是最小值,遍历数组的其余部分......(我想你明白了。

Example:例子:

3,1,2

Assume 3 (pos 1) is smallest.假设 3 (pos 1) 是最小的。 Compare with position 2, 1 < 3, so assume position 2 has smallest value.与位置 2 比较,1 < 3,因此假设位置 2 具有最小值。 Compare with position 3, 3 < 1. Since we are at the end switch smallest with first position.与位置 3 相比,3 < 1。因为我们在第一个位置的末端开关最小。 (position 1 and 2) (位置 1 和 2)

1,3,2

Now, since position 1 is done, start with position 2. Assume 3 (position 2) is the smallest value.现在,由于位置 1 已经完成,从位置 2 开始。假设 3(位置 2)是最小值。 Compare with position 3 (2).与位置 3 (2) 进行比较。 2 < 3, so assume position 3 has smallest value. 2 < 3,因此假设位置 3 具有最小值。 Since we are at the end of the array we switch position 2 and 3由于我们在数组的末尾,我们切换位置 2 和 3

1,2,3

Done完毕

Selection sort is a sorting algorithm in which the smallest element is picked from an unsorted array and moved to the beginning of the array.选择排序是一种排序算法,其中最小的元素从未排序的数组中挑选出来并移动到数组的开头。 In your case first find min value index from second for loop and swap outside on that loop.在您的情况下,首先从第二个 for 循环中找到最小值索引,然后在该循​​环之外进行交换。

private static void selectionSort(int[] arr) {私人静态无效选择排序(int [] arr){

        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int min = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
                }
            }
            if (min != i) {
                int temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM