Program opened below. You can scroll through the algorithm, Java code and output.

Sort Two Arrays Using Insertion Sort

Download .java

Question

Accept two integer arrays, sort each in ascending order using insertion sort and display both arrays.

Step 1: Start the program and accept the size and elements of the first array. Step 2: Accept the size and elements of the second array. Step 3: Define a sorting method that receives an integer array. Step 4: Begin insertion sort at the second element of the array. Step 5: Store the current element as the key. Step 6: Compare the key with the elements to its left. Step 7: Shift each larger element one position to the right. Step 8: Continue shifting until the correct insertion position is found. Step 9: Insert the key at that position. Step 10: Repeat until the entire array is sorted. Step 11: Apply the method separately to both arrays. Step 12: Display the elements of each sorted array on separate lines. Step 13: Stop the program.
Java
import java.util.*;
class SortTwoArrays
{
    static void sort(int[] a)
    {
        for (int i = 1; i < a.length; i++)
        {
            int key = a[i], j = i - 1;
            while (j >= 0 && a[j] > key)
            {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = key;
        }
    }
    static void display(int[] a)
    {
        for (int i = 0; i < a.length; i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Size of first array: ");
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
        {
            a[i] = sc.nextInt();
        }
        System.out.print("Size of second array: ");
        int m = sc.nextInt();
        int[] b = new int[m];
        for (int i = 0; i < m; i++)
        {
            b[i] = sc.nextInt();
        }
        sort(a);
        sort(b);
        System.out.print("First sorted array: ");
        display(a);
        System.out.print("Second sorted array: ");
        display(b);
    }
}
Input: Array 1: 4 1 3; Array 2: 8 2 5 Output: First sorted array: 1 3 4; Second sorted array: 2 5 8
← Previous Program 58 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.