Ten classic sorting algorithms -- selective sorting

Keywords: Java C

1. Algorithm steps

First, the smallest (large) element is found in the unsorted sequence and stored at the beginning of the sorted sequence.

Then continue to find the smallest (largest) element from the remaining unsorted elements, and put it at the end of the sorted sequence.

Repeat the second step until all elements are sorted.

2. for example

Array [2, 5, 4, 9, 7, 11, 6]

First sort [2, 5, 4, 9, 7, 11, 6]

Second order [2, 4, 5, 9, 7, 11, 6]

Third sort [2, 4, 5, 9, 7, 11, 6]

Fourth order [2, 4, 5, 6, 9, 11, 7]

Fifth order [2, 4, 5, 6, 7, 11, 9]

Sixth order [2, 4, 5, 6, 7, 9, 11]

3.C language implementation selection and sorting:

void swap(int *a,int *b) //Exchange two numbers
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
void selection_sort(int arr[], int len) 
{
    int i,j;

        for (i = 0 ; i < len - 1 ; i++) 
    {
                int min = i;
                for (j = i + 1; j < len; j++)     //Visit elements that are not sorted
                        if (arr[j] < arr[min])    //Current minimum found
                                min = j;    //Record minimum
                swap(&arr[min], &arr[i]);    //Exchange
        }
}

4. Implement selective sorting with java language

import java.util.Random;
import java.util.Arrays;

public class SelectionSort {
    public static void main(String args[]){
        int []arr = new int[10];
        for(int i = 0;i<arr.length;i++){
            Random ran = new Random();
            arr[i] = ran.nextInt(100);
        }
        System.out.println(Arrays.toString(arr));
        System.out.println("-------------Selection sort-----------");
        for(int i = 0;i < arr.length-1;i++){
            int min = i;
            for(int j=i+1;j<arr.length;j++){
                if(arr[min]>arr[j]){
                    min = j;
                }
            }
            if(i != min){
                arr[i]^=arr[min];
                arr[min]^=arr[i];
                arr[i]^=arr[min];
            }
            System.out.println(Arrays.toString(arr));
            }
        System.out.println("------------------------");
        }
    }

 

Posted by irishred8575 on Wed, 13 Nov 2019 08:24:50 -0800