- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to implement insertion sort
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
Algorithm
1.If it is the first element, it is already sorted. return 1; 2.Pick next element 3.Compare with all elements in the sorted sub-list 4.Shift all the elements in the sorted sub-list that is greater than the value to be sorted 5.Insert the value 6.Repeat until the list is sorted
Example
public class InsertionSort { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; for (int i=1 ;i< size; i++){ int val = array[i]; int pos = i; while(array[pos-1]>val && pos>0){ array[pos] = array[pos-1]; pos = pos-1; } array[pos] = val; } for (int i=0 ;i< size; i++){ System.out.print(" "+array[i]); } } }
Output
10 20 25 57 63 96
Advertisements