Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Java program for Insertion sort . Arrange elements using Insertion Sort with tutorial

The insertion sort is a simple comparison sort algorithm. Each iteration of insertion sort removes an element from the input array and inserts it into the correct position in the array being sorted. Insertion sort keeps the left side of the array is sorted . At each iteration , a[i] is inserted at the appropriate position in the sorted array and i is increased. . The resulting array after ith iterations will have i+1 sorted elements from the left (i.e. a[1..i+1]) . Insertion sort is similar to selection sort. Advantage of Insertion sort is that it only traverse as many elements as required to find the right location , while selection sort must traverse all remaining elements to find the absolute smallest element.
Suppose we have the elements a[1..n] to be sorted. At each iteration of the algorithm, the array has two parts .For the i th iteration , first part is a[1..i+1] which is sorted, the second part a[i+2..n] is still unsorted . Assume that a[i+2] is assigned to a temp variable. In order to insert element a[i+2] into the sorted part, it is compared with a[i+1], a[i], a[i-1], a[i-2] , etc. Suppose a[i-1] is the appropriate position to insert , then the elements a[i+1] is shifted to a[i+2] and a[i] is shifted to a[i+1]. a[i-1] is shifted to a[i] , and temp value is inserted into a[i-1] .
Insertion sort is vey simple and efficient for small input data. It is much less efficient on large data .
Example : Now we have the following elements to be sorted . For each iterations , we can see the sorted and unsorted elements. The bold elements are sorted on each iteration.
6, 4,2, 9,3, 1

Iteration 1
4 6 2 9 3 1
Iteration 2
2 4 6 9 3 1
Iteration 3
2 4 6 9 3 1
Iteration 4
2 3 4 6 9 1
Iteration 5
1 2 3 4 6 9

The following is the code for Inssertion Sort
   
public class InsertionSort {
public static void main(String[] args) {
int array[] = { 6, 4,2, 9,3, 1 };
System.out.println("Given Elements ");
for (int k = 0; k< array.length; k++) {
System.out.print(array[k] + " ");
}
int j, temp;
// Logic for Insertion Sort
for (int i = 1; i < array.length; i++) {
temp = array[i];
j = i;
while ( j>0 && (array[j-1] > temp)) {
array[j] = array[j - 1];
j = j - 1;
}
array[j] = temp;
}
System.out.println("\nSorted Elements ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}


Output:
D:\as2\JF4>java InsertionSort
Given Elements
6 4 2 9 3 1
Sorted Elements
1 2 3 4 6 9
Read more...

How to Sort HashMap by Values . Write Own Compare Method in Java Example

We can sort the Hashmap by putting all values in a TreeMap . By default TreeMap is sorted by Keys. To sort it by values , we have to write own compare method of comparator interface. The compare method compares its two arguments . By default two arguments are objects which is having key of Map. If both arguments are equal then it returns 0 . If first argument is less than the second argument , returns a negative integer, If first argument is greater than the second argument , returns a Positive integer. Now we have to sort by values. So we have to get the values using key i.e map.get(key) . Now we have to write our own logic to compare the values . The return value will be 0 or 1 or -1 . If more than one elements are equal it adds only the first value. If both arguments are equal means it returns 0 that means Hashmap is having duplicate values. As HashMap does not allow duplicate values ,to allow duplicate values , we have to return other than 0 value. In our example , when both values are equal , we compare both keys rather than values , thus returns other than 0. The following program is compatible for sorting of strings and also positive numbers. Negative numbers are sorted properly because we are using String.compareTo to compare two values. So it is always better to pass same type of values and change the compareTo logic accordingly. For example if all the values are integer means , the logic will be Integer e1 = (Integer)thisMapValues.get(o1); Integer e2 = (Integer) thisMapValues.get(o2); if (e1==e2) return return String.valueOf(o1).compareTo(String.valueOf(o2)) ; else if (e1<e2) return -1 ; else return 1;

import java.util.*;
public class HashMapSortValue{
private static class OwnCompare implements Comparator
{
private Map thisMapValues = null;
public OwnCompare (Map mapValues)
{
super();
thisMapValues = mapValues;
}

public int compare(Object o1, Object o2)
{
String e1 = String.valueOf(thisMapValues.get(o1));
String e2 = String.valueOf( thisMapValues.get(o2));
if (e1.compareTo(e2)==0) return String.valueOf(o1).compareTo(String.valueOf(o2)); else return e1.compareTo(e2);

}
}

public static void main(String[] args) {
Map hm = new HashMap();
hm.put ("Employee1", 60000);
hm.put ("Employee2", 50000);
hm.put ("Employee2", "absent");
hm.put ("Employee3", 25000);
hm.put ("Employee4","retired");
hm.put ("Employee5","absent");
hm.put ("Employee6",20000);
hm.put ("Employee7",20000);
hm.put ("Employee8",50000);
hm.put ("Employee9",60000);
System.out.println("List Before Sorting : " + hm);
SortedMap sortedByValue = new TreeMap(new HashMapSortValue.OwnCompare(hm));
sortedByValue.putAll(hm);
System.out.println("List After Sorting by Value " +sortedByValue);
}
}


Output :

Read more...

 
Copyright 2011 Java Online