Simple Sort

package com.exuan.simplesort;

public class SimpleSort {
    public static void main(String[] args)
    {
        int[] data = {12,10,46,3,1,5,4,7,8,9,2,0,6};
        for(int i = 0; i < data.length; i++)
        {System.out.print(data[i] + ",");}
        Sort s = new Sort();
        s.selectionSort(data);
        System.out.println();
        for(int i = 0; i < data.length; i++)
        {System.out.print(data[i] + ",");}
    }
   
    //Bubble sort
    //Time complexity O(N2)
    void bubbleSort(int[] data)
    {
        //outer loop from right to left
        for(int i = data.length - 1; i > 1; i--)
        {
            //inner loop from left to right
            for(int j = 0; j < i; j++)
            {
                if(data[j] > data[j + 1])
                {
                    int temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }
    }

    //Selection sort
    //Time complexity O(N2)
    void selectionSort(int[] data)
    {
        int min = 0;
        //outer loop from left to right
        for(int i = 0; i < data.length - 1; i++)
        {
            //find the min value to swap with the left
            min = i;
            for(int j = i + 1; j < data.length; j++)
            {
                if(data[j] < data[min])
                {
                    min = j;
                }
            }
            int temp = data[i];
            data[i] = data[min];
            data[min] = temp;
        }
    }

    //Insertion sort
    //Time complexity O(N2)
    void insertionSort(int[] data)
    {
        int i,j;
        //outer loop from left to right
        for(i = 1; i < data.length; i++)
        {
            int temp = data[i];
            /* inner loop from right to left to find the appropriate
             * position to insert the value
             */
            for(j = i - 1; j >= 0; j--)
            {
                if(data[j] > temp)
                {
                    data[j+1] = data[j];
                }
                else
                {
                    break;
                }
            }
            data[j+1] = temp;
        }
    }
}

原文地址:https://www.cnblogs.com/jayceli/p/2428615.html