简体   繁体   English

Java中的简单插入排序

[英]Simple Insertion Sort in Java

I had written a simple insertion sort program but the output is not coming correctly.我写了一个简单的插入排序程序,但输出不正确。

class InsertionSort{
    public static void main(String h[]){
    int[] a = {5,4,3,2,1};
    int i,j,temp;
        for(i=1;i<a.length;i++){
            j = i-1; 
            while(i>0 && a[j] > a[i]){
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        for(int x=0; x<a.length;x++){
            System.out.println(a[x]);   
        }
    }
}

At the top of the outer loop the array is sorted below element i .在外部循环的顶部,数组被排序在元素i之下。 You don't want to move i back down into the array.您不想将i移回数组。 In the inner loop j moves the new element that starts at i down into the sorted array by repeatedly switching with the next one down.在内部循环中, j通过与下一个向下重复切换,将从i开始的新元素向下移动到已排序的数组中。

for (i = 1; i < a.length; i++){
    for (j = i; j > 0 && a[j-1] > a[j]; j--){
        temp = a[j];
        a[j] = a[j-1];
        a[j-1] = temp;
    }
}

Very Simple approach非常简单的方法

public static void main(String[] args) {
    int[] array = {100, 12, 31, 5, 4, 3, 2, 1};

    for (int i = 1; i < array.length; i++) {
        for (int j = i; j > 0; j--) {
            if (array[j - 1] > array[j]) {
                int temp = array[j];
                array[j] = array[j - 1];
                array[j - 1] = temp;
            }
        }
    }
    System.out.println(Arrays.toString(array));
}

The simplest is that.最简单的就是这样。

public class JavaApplication1 {

    public static void main(String[] args) {
        int arry[] = {5, 4, 2, 1, 9, 6, 3};
        InsertionSort(arry);

    }

    private static void InsertionSort(int[] arry) {
    int startIndex = 0;
    for (int i = 1; i < arry.length; i++) {
        for (int j = 0; j < i; j++) {
            if (arry[i] < arry[j]) {
                int temp = arry[j];
                arry[j] = arry[i];
                arry[i] = temp;
            }
        }
        //test
        for (int g = 0; g < arry.length; g++) {
            System.out.print(arry[g] + " ");
            if (g == i) {
                System.out.print("|");
            }
        }
    }
}

We can follow simple approach using cursor.我们可以使用游标遵循简单的方法。 Kindly find below.请在下面找到。

public static void insertionSort(int[] elements) {
    for(int i=1;i<elements.length;i++) {            
        int cursor = i;
        for(int j=i;j>=0;j--) {
            if(elements[j]>elements[cursor]) {
                int temp = elements[j];
                elements[j] = elements[cursor];
                elements[cursor] = temp;                    
                cursor = j;                 
            }

        }
    }
}

Please let me know your's feedback so it is most helpful to improve from myside请让我知道您的反馈,以便从我身边改进最有帮助

import java.security.SecureRandom; import java.util.Arrays; public class Sorting { public static void insertionSort(int[] data){ for(int i=1;i<data.length;i++){ int insert = data[i]; int index = i; while(0<index && insert < data[index-1]){ data[index]=data[index-1]; index--; } data[index]=insert; } } public static void main(String[] args) { SecureRandom generator = new SecureRandom(); int[] data = generator.ints(30, 10, 20).toArray(); insertionSort(data); System.out.println("Sorted array: "+Arrays.toString(data)); } }
public static int[] doInsertionSort(int[] input) {
    int reverse;
    for (int i = 1; i < input.length; i++) {
        for (int j = i; j > 0; j--) {

            System.out.println("compare " + input[j - 1] + " to " + input[j]);

            if (input[j] < input[j - 1]) {
                reverse = input[j];
                System.out.println("Reverse: "+ reverse);

                input[j] = input[j - 1];
                input[j - 1] = reverse;

                new printNumbers(input);
            }
        }
    }
    return input;
}

 printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {

        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}
public static void insertionsort(){
            Scanner sc = new Scanner(System.in);

                    int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
                    arr(input);
        }
        private static void printNumbers(int[] input) {
            for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
        }

        public static void arr (int array[]){    
                int n = array.length;
        for (int j = 1; j < n; j++) {
            int key = array[j];
            int i = j-1;
            while ( (i > -1) && ( array [i] > key ) ) {
                array [i+1] = array [i];
                i--;
            }
            array[i+1] = key;
            printNumbers(array);

    }
}    

Insertion Sort插入排序

public class InsertionSort {

    public static void main(String args[]){
        int[] arry1 = {55,12,43,27,54,34,77,3,15,19};
        int[] arry2 = insertionSort(arry1);
        System.out.println("Insertion Sort Demo:");
        for(int i:arry2){
            System.out.print(i);
            System.out.print(" ");
        }
    }

    public static int[] insertionSort(int[] arr){

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

}

Program Output:程序输出:

Insertion Sort Demo:插入排序演示:

3 12 15 19 27 34 43 54 55 77 3 12 15 19 27 34 43 54 55 77

This is tested and works这是经过测试并有效的

public static int[] insertionSort(int[] array) {
    int temp, j;

    for(int i = 1; i < array.length; i++) {
        temp = array[i];

        for (j = i - 1; j >= 0; j--) {
            if (array[j] > temp) {
                array[j+1] = array[j];
            } else {
                break;
            }
        }
        array[j + 1] = temp;
    }

    return array;
}
Scanner s = new Scanner(System.in);
        System.out.println("Enter the nos");
        num = s.nextInt();

        System.out.println("Enter the "+num+" integers");
        int array []= new int[num];
        for(int count = 0;count<num; count++ )
        {
            array[count] = s.nextInt(); 
        }

        for(int i = 0;i<array.length;i++)
        {
            key = array[i];
            j = i-1;
            while(j>=0 && array[j]>key)
            {
                array [j+1] = array[j];
                j=j-1;
            }

            array[j+1] = key;
        }

        System.out.println("Sorted array");

        for(int i=0;i<array.length;i++)

        {
            System.out.println(array[i]);
        }

Insertion Sort (ES6)插入排序 (ES6)

(in case someone needs it) (以防有人需要)

 // Insertion Sort In-Place function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { for (let j = i; j > 0; j--) { if (arr[j] < arr[j - 1]) { [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; } else { break; } } } return arr; } const arr = [5,1,9,2,0,6,4,3,8,7]; console.log(insertionSort(arr)); // [0,1,2,3,4,5,6,7,8,9]

Insertion sort is a another sorting algorithm for sorting array elements.This algorithm is better than selection sort algorithm or bubble sort algorithm.Worst case time complexity and average case time complexity is (n^2).Best case time complexity is (n) .Worst case space complexity is (n) and best case space complexity is constant(1).Let's see how to implement insertion sort algorithm.插入排序是另一种对数组元素进行排序的排序算法。该算法优于选择排序算法或冒泡排序算法。最坏情况时间复杂度和平均情况时间复杂度为 (n^2)。最佳情况时间复杂度为 (n) 。最坏情况空间复杂度为(n),最好情况空间复杂度为常数(1)。让我们看看如何实现插入排序算法。

import java.util.Scanner;

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

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

    int[] num=new int[n];
    int i,j,tmp,tmp2;


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

    for(i=1;i<n;i++){
        tmp=num[i];
        for(j=0;j<i;j++){
            if(num[i-j-1]>tmp){
                tmp2=num[i-j-1];
                num[i-j-1]=tmp;
                num[i-j]=tmp2;
            }
            else{
                break;
            }
        }
    }

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

} }

public int[] insertionSort(int[] list)
{
for (int i = 1; i < list.length; i++)
{
int key = list[i];
int j = i - 1;
while (j >= 0 && key < list[j])
{
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
j--;
}
}

return list;
}
/*this program sort in ascending order by insertion sort */  
class InsertionSort{
public static void main(String h[]){
int[] a = {100,12,31, 5, 4, 3, 2, 1 };
int i, j, temp;
    for (i = 1; i < a.length; i++)
    {
        j = i - 1;
        while (j >= 0 && a[j] > a[i] )
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i=j;
            j--;

        }
    }
for(int x=0; x<a.length;x++){
    System.out.println(a[x]);   
  }
}
}
/*this program sort in descending order by insertion sort */  
class InsertionSort{
public static void main(String h[]){
int[] a = {100,12,31, 5, 4, 3, 2, 1 };
int i, j, temp;
    for (i = 1; i < a.length; i++)
    {
        j = i - 1;
        while (j >= 0 && a[j] < a[i] )
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i=j;
            j--;

        }
    }
for(int x=0; x<a.length;x++){
    System.out.println(a[x]);   
  }
}
}

While loop is unnecessary here,虽然这里不需要循环,

                if ((a[j] < a[i]))
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }

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

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