Bubble, selection, insertion sort algorithm

Sorting Algorithm

Sort sorting algorithm also as (Sort Algorithm), the sorting process is a set of data, arranged according to the order specified

Sort of classification

Internal sorting: refers to all the data to be processed are loaded into the internal memory to sort

External sorting method: data is too large to load into memory all, it needs to sort external storage

Both methods (algorithms) measure a program execution time

1. Afterwards statistical methods

This method is feasible, but there are two issues, namely, in order to run performance of the algorithm design for evaluation, you need to actually run the program: Second time statistics of income depends on environmental factors computers hardware, software, etc., which ways to run in the same state at the same computer, in order to compare the algorithm is faster

2. The ex-ante estimation method

Be judged by analyzing the time complexity of the algorithm is an algorithm better

Time complexity of the algorithm

Time frequency : time spent with an algorithm execution times of the algorithm is proportional to the statement, which statements algorithm executed more often, the more time he spent, a number of execution algorithms statement called the statement frequency or frequency time. denoted as: T (n)

Statistical time frequency: As n increases, the constant term, low-order terms can be ignored coefficients

time complexity

1. In general, the number of repetitions of the operation of the algorithm execution statement is a function of the problem size n, with T (n) represents, if an auxiliary function F (n), such that when n approaches infinity , T (n) / f (n) is not equal to zero limit constant, called f (n) is T (n) is a function of the same order. Denoted by T (n) = O (f (n)), said O (f (n)) is a progressive time complexity of the algorithm, time complexity Acronym

2.T (n) different, but it may be the same time complexity

The method of computation time complexity 3

  1. Instead of adding all the constant T (n) = n ^ 2 + 7n + 6 => T (n) = n by a constant running time of 1 ^ 2 + 7n + 1
  2. Running times after the modification function, leaving only the highest order term T (n) = n ^ 2 + 7n + 1 => T (n) = n ^ 2
  3. Coefficient T (n) removing the highest order term = n ^ 2 => T (n) = n ^ 2

Common time complexity

1. Constant order O (1): no matter how many lines of code execution, a complex structure as long as there is no circulation, the time complexity of this code are to O (1)

2. order O (log2n):

//说明:在while循环里面,每次都将i乘以2,乘完之后,i距离n就越来越近了,假设循环x次之后,退出循环,也就是说2的x次方等于n,那么x=log2n也就是说当循环log2n次以后,这个代码就结束了。因此这个代码的时间复杂度为:O(log2n)
//如果a的x次方等于N(a>0,且a不等于1),那么数x叫做以a为底N的对数(logarithm),记作x=logaN。其中,a叫做对数的底数,N叫做真数
//这段代码执行log2^1024次
public static void main(String[] args) {
      int count=0;
      int i=1;
      int n=1024;
      while(i<n) {
          i=i*2;
          count++;
      }
      //log2^1024=10
      System.out.println(count);//10
      
    }

3. The linear order O (n): for cyclic code is executed n times, the time consumed by him is n varies with changes in

4 linear logarithmic order O (nlog2n): linear logarithmic order O (nlogN) actually very easy to understand, the time complexity is O (logn) code loop N times, then the time complexity is n * O (logN)

The square of the order O (n ^ 2): If the O (n) in the nested code again, his time complexity is O (n ^ 2),

//这段代码其实就是嵌套了2层n循环,他的时间复杂度就是O(n*n)
for(x=1;i<=n;x++) {
     for(x=1;i<=n;x++) {
            j=i;
            j++;
        }
    }

6. the cubic order O (n ^ 3): equivalent to three cycles for

7.k th order (n ^ K)

8. exponential order O (2 ^ n)

Space complexity

Similar to the discussion time complexity, space complexity of the algorithm defined for the algorithm lock-consuming storage space, he is also a function of the scale of the problem n

Bubble Sort

Sorting will be determined every time a maximum

package sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class BubbleSort {
    public static void main(String[] args) {
        //int arr[] = {3,9,-1,10,-2};
        //时间复杂度O(n^2)
        //测试冒泡排序的速度,要求排序80000个数字
        int[] arr = new int[80000];
        for(int i=0;i<arr.length;i++) {
            //每循环一次就添加一个元素
            arr[i]=(int)(Math.random()*80000);
        }
        Date data1 = new Date();
        System.out.println(data1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(data1);
        System.out.println("开始时间"+dateStr);
        System.out.println("排序进行中........");
        //对数组进行排序
        bubbleSort(arr);
        Date data2 = new Date();
        String dateStr2 = sdf.format(data2);
        System.out.println("开始时间"+dateStr2);
        System.out.println("排序结束");
        
    }
    public static void bubbleSort(int[] arr) {
        int temp = 0;//临时变量
        boolean b = false;
        for(int i=0;i<arr.length-1;i++) {//一共需要进行arr.length-1次排序
            for(int j=0; j<arr.length-1-i;j++) {
                if(arr[j]>arr[j+1]) {
                    b=true;
                    temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
            //System.out.println("第"+(i+1)+"次冒泡。。。。。");
            //System.out.println(Arrays.toString(arr));
            if(!b) {
                break;
            }else {
                b=false;//重置为false,是因为已经有进行过排序
            }
        }
    }
}
//冒泡排序平均15秒

Selection Sort

Sorting each have a minimum value determined

package sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class SelectSort {
    public static void main(String[] args) {
        int[] arr = new int[80000];
        for(int i=0;i<arr.length;i++) {
            //每循环一次就添加一个元素
            arr[i]=(int)(Math.random()*80000);
        }
        Date data1 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(data1);
        System.out.println("开始时间"+dateStr);
        System.out.println("排序进行中........");
        selectSort(arr);
        Date data2 = new Date();
        String dateStr2 = sdf.format(data2);
        System.out.println("开始时间"+dateStr2);
        System.out.println("排序结束");
        //System.out.println(Arrays.toString(arr));
    }
    //选择排序arr[0]=min
    public static void selectSort(int[] arr) {
        for(int i=0;i<arr.length-1;i++) {
            int minIndex = i;//假定最小索引为0
            int min = arr[i];//假定最小值是arr数组的0索引
            for(int j = 1+i;j<arr.length;j++) {
                if(min > arr[j]) {
                    min=arr[j];//重置最小值
                    minIndex=j;//重置最小值得索引 
                }
            }
            if(minIndex !=i) {//表示minIndex没有放生交换
                arr[minIndex] = arr[i+0];//101赋值给索引3
                arr[0+i] = min;//1赋值给索引0
            }
        }
    }
    
}
//选择排序平均3秒

Insertion Sort

Sorting insert is an internal sort, for the elements to be sorted in a way to find the proper insertion position of the element, it has the purpose of ordering

Insertion sort of thinking: is to be seen as an array of two tables, a table stored ordered elements, a table storage disorderly elements, ordered list of initial elements arr [0], by comparison with arr [0] of to determine the position of the insertion, and so on.

package sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class InsertSort {
    public static void main(String[] args) {
        int[] arr = new int[80000];
        for(int i=0;i<arr.length;i++) {
            //每循环一次就添加一个元素
            arr[i]=(int)(Math.random()*80000);
        }
        Date data1 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(data1);
        System.out.println("开始时间"+dateStr);
        System.out.println("排序进行中........");
        insertSort(arr);
        Date data2 = new Date();
        String dateStr2 = sdf.format(data2);
        System.out.println("开始时间"+dateStr2);
        System.out.println("排序结束");
        //int arr[] = {3,9,-1,10,-2};
    }
    
    public static void insertSort(int[] arr) {
        for(int i = 1;i < arr.length; i++) {
            int insertVal = arr[i];
            int insertIndex = i-1;//i-1的意思是要把插入的数与前一个数比较
            //insertIndex >=0 防止越界
            //insertVal < arr[insertIndex])
            while(insertIndex >=0 && insertVal < arr[insertIndex]) {
                arr[insertIndex+1] = arr[insertIndex];//往后移
                insertIndex--;//继续与前面的数比较
            }
            if(insertIndex+1!=i) {
                arr[insertIndex+1] = insertVal;
            }
        }
    }
}
//平均时间5秒

Guess you like

Origin www.cnblogs.com/train99999/p/11123096.html