import java.util.Scanner; public class Insertion { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of array: "); int n = sc.nextInt(); int arr[] = new int[n]; System.out.println("enter array elements: "); for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } for (int i = 1; i < arr.length; i++) { int current = arr[i]; int j; for (j = i - 1; j >= 0 && arr[j] > current; j--) { arr[j + 1] = arr[j]; } arr[j + 1] = current; } System.out.println("sorted array: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter