Selection Sort (C ++, Java, Python realization)

Selection Sort sorting algorithm, the selection sort, sort selected basic idea is described as: In each pass n-i + 1 (i = 1,2, ..., n-1) th recording key selected as having the smallest recorded the i-th sequence in the sequence records. Specifically, assuming that the length n of the array ARR, to be arranged in ascending order, then the start of the n digital min1 minimum is found, if the position is not the minimum min1 leftmost array (i.e. not equal min1 arr [ 0]), then the minimum min1 and ARR [0] exchange, and then find the minimum value min2 in the remaining n-1 numbers, if not equal to the minimum value min2 arr [1], the exchange of these two numbers, And so on, until the array arr ordered.

Algorithmic process

For chestnut (first pass sorting process)

The original sequence: 3,44,38,5,47,15,36, 26,27,2,46,4,19,50,48

1) After selecting the sorting process into two parts ordered and disordered, random sequence is started

Results: 3,44,38,5,47,15,36, 26,27,2,46,4,19,50,48

2) Remove the smallest element 2 from the random sequence, the random sequence with the 2 first switching element, generated at this time contains only one element of the ordered sequence, minus a random sequence

Results: {2} {44,38,5,47,15,36, 26,27,3,46,4,19,50,48

3) from the random sequence smallest element 3, with the first switching element 3 unordered sequence, this time to produce an ordered sequence of only two elements, unordered sequence minus one

Results: {2,3} {38,5,47,15,36, 26,27,44,46,4,19,50,48}

4) from the random sequence smallest element 4, 4 with the first switching element unordered sequence, generated at this time ordered sequence containing three elements, unordered sequence minus one

Results: {2,3,4, {5,47,15,36}, 26,27,44,46,38,19,50,48}

5) Remove the random sequence from the smallest element 5,5 is the smallest at this time sequence disorder, without exchange

Results: {2,3,4,5} {47,15,36, 26,27,44,46,38,19,50,48}

6) Remove the random sequence from the smallest element 15, 15 with the switching element of a first random sequence, generated at this time ordered sequence comprising five elements, unordered sequence minus one

Results: {2,3,4,5,15} {47,36, 26,27,44,46,38,19,50,48}

7) The above operations are repeated sequentially until the last element is only random sequence

8) The last element is the largest element 50 is certainly disorderly ordering direct production of an ordered sequence

Results: {} 2,3,4,5,19,26,27,36,38,44,46,47,48,50

Finally, if you do not understand this process, then put a small series action figure, let everyone a better understanding of this process:

FIG insertion sort dynamic analysis

Analysis algorithms over the next insertion sort, we have to share this exciting moment of the code:

C ++ implementation code insertion sort:

#include <iostream>
using namespace std;
#include <vector>
#include <time.h>
vector<int> get_random(int n, int N);
const int MAX_NUM=10000;
int data[100];//定义一个产生数组储存100个随机数
void SelectSort(int n);//选择排序
void output(int n);
void Swap(int i,int j);
int main() 
{
  srand((unsigned int)time(0));
  vector<int> randsample=get_random(100,MAX_NUM);//产生100个0-MAZX_NUM的随机数,每次产生的随机数不一样
  int size=randsample.size();
  //输出最开始时未排序时的顺序:
  cout<<"随机数的顺序:"<<endl;
  for(int i=0;i<randsample.size();i++)
  {
    cout<<randsample[i]<<" ";
  }
  cout<<endl;
  clock_t start,finish;//定义一个测量一段程序运行时间的前后值
  double totaltime;//总的运行时间
  
  //测试选择排序
  cout<<"执行选择排序后:"<<endl;
  for(int i=0;i<randsample.size();i++)
  {
    data[i]=randsample[i];
  }
  start=clock();
  SelectSort(size);
  finish=clock();
  output(size);
  totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
  cout<<"运行时间:"<<totaltime<<endl;
}
//产生随机数的函数
vector<int> get_random(int n, int N)
{
  vector<int> vec(N);//N代表初始状态分配的空间大小
  vector<int> out_vec;
  for(int i=0;i<N;++i)
  {
    vec[i]=i;
  }
  for (int i=0;i<n;++i)
  {
    int rand_value=rand()%N;
    out_vec.push_back(vec[rand_value]);
    vec[rand_value]=vec[N-1];//将数组vec的元素
    N--;
  }
  return out_vec;
}
//直接选择排序
void SelectSort(int n)
{
  int i,j;
  int count=0;
  int count1=0;
  for(i=0;i<n;i++)
  {
    int k=i;//在data[i]到data[n-1]找最小排序码元素
    for(j=i+1;j<n;j++){
      if(data[j]<data[k]){
        count++;//当前具有最小排序码的元素
        k=j;
      }
    }
    if(k!=i)
    Swap(i,k);//交换
    count1++;
  }
  cout<<"比较次数: "<<count<<"  移动次数:  "<<count1<<endl;
}
void output(int n)
{
  for(int i=0;i<n;i++)
  {
    cout<<data[i]<<" ";
  }
  cout<<endl;
}
//交换函数
void Swap(int i,int j)
{
  int tem;
  tem = data[j];
  data[j]= data[i];
  data[i] = tem;
}
  

Sort results

Insertion sort Java code implementation

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SelectSort
{
  public static void main(String[] args)
  {
    Object []arr = getRandomNumList(100,0,10000).toArray();
    int[] ins = new int [100] ;
    System.out.println("排序前:");
    for(int i = 0; i < arr.length; i++) {
      String s=arr[i].toString();
      ins[i]= Integer.parseInt( s );
      System.out.println(ins[i]);
      }
    System.out.println("排序后:");
    int[] ins2 = selectsort(ins);
    for(int i = 0; i < arr.length; i++) {
      System.out.println(ins2[i]);
      }
  }
  
  public static int[] selectsort(int[] data){
    int i,j;
    int n = data.length-1;
    for(i=0;i<n;i++)
    {
      int k=i;//在data[i]到data[n-1]找最小排序码元素
      for(j=i+1;j<n;j++){
        if(data[j]<data[k]){//当前具有最小排序码的元素
          k=j;
        }
      }
      if(k!=i)
      {
        int tem;
        tem=data[k];
        data[k]=data[i];
        data[i]=tem;
      }
    }
    return data;
  }
   //定义生成随机数并且装入集合容器的方法
    //方法的形参列表分别为:生成随机数的个数、生成随机数的值的范围最小值为start(包含start)、值得范围最大值为end(不包含end)  可取值范围可表示为[start,end)
    public static List getRandomNumList(int nums,int start,int end){
        //1.创建集合容器对象
        List list = new ArrayList();

        //2.创建Random对象
        Random r = new Random();
        //循环将得到的随机数进行判断,如果随机数不存在于集合中,则将随机数放入集合中,如果存在,则将随机数丢弃不做操作,进行下一次循环,直到集合长度等于nums
        while(list.size() != nums){
            int num = r.nextInt(end-start) + start;
            if(!list.contains(num)){
                list.add(num);
            }
        }
        return list;
    }
}

Python code for insert sequencing

import random
def sort(arr):
    for j in range(len(arr)-1):
        minIndex = j
        for i in range(j+1,len(arr),1):
            if(arr[i] < arr[minIndex]):
                minIndex = i
        arr[j],arr[minIndex] = arr[minIndex],arr[j]

def main():

    arr =[]
    while(len(arr)<100):
        x=random.randint(0,10000)
        if x not in arr:
            arr.append(x)
    sort(arr)
    print(arr)

if __name__ == "__main__":
    main()

Analysis of Algorithms:

Initial direct selection sort number sort code comparing with the arrangement of elements independent of KCN. Run the i-th selecting a minimum number of comparisons needed to sort key element always ni-1 times, where the whole is assumed to be sorted elements of a sequence has n elements. Therefore, the total number of sorting code comparing:

K C N = i = 0 n 2 ( n i 1 ) \displaystyle KCN=\sum_{i=0}^{n-2}{(n-i-1)} =n*(n-1)/2

The number of initial alignment and movement of elements of the sequence of the relevant element. When the initial state is the set of elements to sort by code when ordered from small to large, the number of moving elements RMN = 0, reaches a minimum; the worst case must be exchanged each pass, the total number of mobile elements RMN = 3 (n-1). It's a kind of important elements of the sequence has good efficiency, and this is a great element of scale, while relatively small, but the sort code sequence. Because of this sort of sequence, the time it takes to move the operating time than the comparison operation is much greater, and the time it takes to move operations to other algorithms than the comparison operation time of much larger, the number of operations and other algorithms move We should be much more than the selection sort. Direct selection sort is an unstable sorting method.

These are a few of this sort to share options realization, if there is any deficiencies welcome to point out that message, mutual learning and common progress. Spent hours sorting and hope to gain everyone's support, your support is my motivation, here I will continue to update other sorting algorithms, so stay tuned! Personal blog want to learn other content can also visit my reunion blog (there are hexo build blog and other related content)

Published 19 original articles · won praise 8 · views 620

Guess you like

Origin blog.csdn.net/qq_43336390/article/details/103037214