Question

Problem 2. Write a code implementing Insertion-Sort algorithm.

Preferably java

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

`Hey,

Note: If you have any queries related to the answer please do comment. I would be very happy to resolve all your queries.

public class Main {
/*Function to sort array using insertion sort*/
public static void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
  
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
  
/* A utility function to print array of size n*/
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
  
System.out.println();
}
  
// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
  
sort(arr);
  
printArray(arr);
}
}

Chrome File Edit View History Bookmarks People Tab Window Help 62%O Sun 4:14 AM Q M Inbox - gurkaranpreet.sing X C Computer S

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
Preferably java Problem 2. Write a code implementing Insertion-Sort algorithm.
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
ADVERTISEMENT