Wednesday, December 24, 2014

Java bubble and Array List and java Sort elements of Java Vector



Sort Java Array List in descending order using comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SortArrayListInDescendingOrderExample
          {
public static void main(String[] args)
{
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
Comparator comparator = Collections.reverseOrder();

System.out.println("Before sorting ArrayList in descending order : "
+ arrayList);
Collections.sort(arrayList,comparator);
System.out.println("After sorting ArrayList in descending order : "
+ arrayList);
  }
}

Java Bubble Sort

public class BubbleSort
{
public static void main(String[] args)
{
int intArray[] = new int[]{5,90,35,45,150,3};
System.out.println("Array Before Bubble Sort");
for(int i=0; i < intArray.length; i++)
{
System.out.print(intArray[i] + " ");
}
bubbleSort(intArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
for(int i=0; i < intArray.length; i++)
{
System.out.print(intArray[i] + " ");
  }
}
private static void bubbleSort(int[] intArray)
{
int n = intArray.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
                                
if(intArray[j-1] > intArray[j])
{
temp = intArray[j-1];
intArray[j-1] = intArray[j];
intArray[j] = temp;
             }
         }
      }
   }
}

Sort elements of Java Vector

import java.util.Vector;
import java.util.Collections;
public class SortJavaVectorExample
{
 public static void main(String[] args)
{
Vector v = new Vector();
v.add("1");
v.add("3");
v.add("5");
v.add("2");
v.add("4");
Collections.sort(v);
                System.out.println("Vector elements after sorting in ascending order : ");
for(int i=0; i
System.out.println(v.get(i));
   }
}

No comments:

Post a Comment