Wednesday, December 24, 2014

Java array list pro



Sort elements of Java Array List

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

Java Bubble Sort Descending Order

public class BubbleSortDescendingOrder
{
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;
       }
     }
   }
 }
}

Java Sort byte Array

import java.util.Arrays;
public class SortByteArrayExample
{
 public static void main(String[] args)
{
 byte[] b1 = new byte[]{3,2,5,4,1};
System.out.print("Original Array :\t ");
for(int index=0; index < b1.length ; index++)
System.out.print("  "  + b1[index]);
Arrays.sort(b1);
System.out.print("\nSorted byte array :\t ");
for(int index=0; index < b1.length ; index++)
System.out.print("  "  + b1[index]);
byte[] b2 = new byte[]{5,2,3,1,4};
Arrays.sort(b2,1,4);
System.out.print("\nPartially Sorted byte array :\t ");
for(int index=0; index < b2.length ; index++)
System.out.print("  "  + b2[index]);
  }
}

No comments:

Post a Comment