Java Array Sort - Insertion Sort

Insertion sort is to find the position of a new element from an already sorted array

Two layers of loops:
  1. The outer loop is responsible for getting an element that is not sorted. The outer loop starts at 1.
  2. The inner loop is responsible for finding a position for an unsorted element in the sorted array.

public class InsertDemo {
	public static void main(String[] args) {
		int[] arr = new int[] { 4, 3, 2, 1 };

		int[] arr2 = getInsert(arr);
		for (int a : arr2) {
			System.out.print(a + " ");
		}
	}

	public static int[] getInsert(int[] arr3) {
		// 4,3,2,1
		// first comparison: i=1 j=1 3,4,2,1
		// Second comparison: i=2 j=2 3,2,4,1
		// 			   j=1 2,3,4,1
		// third comparison i=3 j=3 2,3,1,4
		// 			  j=2 2,1,3,4
		// 			  j=1 1,2,3,4
		for (int i = 1; i < arr3.length; i++) {
			for (int j = i; j > 0; j--) {
				if (arr3[j - 1] > arr3[j]) {
					int temp = arr3[j - 1];
					arr3[j - 1] = arr3[j];
					arr3[j] = temp;
				}
			}
		}
		return arr3;
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641899&siteId=291194637