Friday, December 19, 2014
Binary Search
public class BinarySearchTest {
public static void main(String[] args){
int[] iarr = {1,3,5,7};
int key = 5;
int index = binarySearch(iarr,key);
System.out.print(key+" is at index "+index);
}
private static int binarySearch(int[] iarr, int key) {
int start = 0;
int end = iarr.length-1;
int mid = 0;
while (start<=end){
mid = (start+end)/2;
if (key==iarr[mid]) {
return mid;
}
else if (key<iarr[mid]){
end = mid -1;
}
else if (key>iarr[mid]){
start = mid+1;
}
}
return -1;
}
}
OUTPUT
5 is at index 2
Sunday, December 7, 2014
SortCollectionByComparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortCollectionByComparator {
public static void main(String[] args){
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee("John",10));
empList.add(new Employee("Alex",20));
empList.add(new Employee("Mark",30));
Collections.sort(empList,new SortEmpByNameComparator());
for (Employee emp: empList){
System.out.println(emp.getEmpName()+" "+emp.getEmpId());
}
}
}
public class Employee {
private String empName;
private Integer empId;
public Employee() {
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public Employee(String empName, Integer empId){
super();
this.setEmpName(empName);
this.setEmpId(empId);
}
}
import java.util.Comparator;
public class SortEmpByNameComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getEmpName().compareTo(emp2.getEmpName());
}
}
OUTPUT
Alex 20
John 10
Mark 30
Tuesday, December 2, 2014
Sort HashMap on Value
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MapSortByValue {
public static void main(String[] args){
Map map = new HashMap();
map.put("a", 1);
map.put("c", 3);
map.put("b", 2);
Set set = map.entrySet();
List list = new ArrayList(set); // convert set to list
// before sorting
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
Collections.sort(list, new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Map.Entry<String, Integer> entry1 = (Map.Entry<String, Integer>) o1;
Map.Entry<String, Integer> entry2 = (Map.Entry<String, Integer>) o2;
return (entry1.getValue()).compareTo(entry2.getValue());
}
});
// after sorting
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
Subscribe to:
Posts (Atom)