Question

For this lab you will implement one sorting algorithm. You can choose from either insertion sort...

For this lab you will implement one sorting algorithm. You can choose from either insertion sort or bubble sort.

If you choose insertion sort these lines of code must work (define your methods/functions to work accordingly)

---------------Java-------------------

System.out.println(Arrays.toString(insertionSort(new int[] {5,2,4,3,10,7,1,9,6,8})));

System.out.println(Arrays.toString(bubbleSort(new int[] {5,2,4,3,10,7,1,9,6,8})));

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.*;

public class InsertionSort

{

    public static int[] insertionSort(int[] a)

    {

        int i, j, temp;

       

        for (i = 1; i < a.length; i++)

        {

            // store the current element in temp

            temp = a[i];

           

            // set j to i - 1

            j = i - 1;

            // all elements greater than temp are

            // shifted 1 position right

            while (j >= 0 && a[j] > temp)

            {

                // shifted 1 position right

                a[j+1] = a[j];

                j--;

            }

           

            a[j + 1] = temp;

        }

       

        return a;

    }

   

    public static void display(int a[])

    {

        int n = a.length;

        for (int i=0; i<n; ++i)

            System.out.print(a[i] + " ");

        System.out.println();

    }

   

    public static void main(String[] args)

    {

        System.out.println(Arrays.toString(insertionSort(new int[] {5,2,4,3,10,7,1,9,6,8})));

    }

}


Sample Output

Add a comment
Know the answer?
Add Answer to:
For this lab you will implement one sorting algorithm. You can choose from either insertion sort...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT