Tuesday, July 19, 2011

Sorting (Linear)

import java.util.Scanner;
public class sortTest
{
//find the minimum of two numbers
public static int findMinimum(double[] A, int i)
{
int j, min = i;

for(j=i+1; j if(A[j] < A[min]) min = j;
return min;



}

//swap A[i] and A[j]
public static void swap(double[] A, int i, int j)
{
double temp = A[i];
A[i] = A[j];
A[j] = temp;
}

//selection sort
public static void selectionSort(double[] A)
{
int i , j;
for ( i = 0; i {
int min = findMinimum(A,i);
swap(A,i,min);
}
}


//prints the sorted array
public static void printAllSorted(double[] A)
{
for(int i=0; i {
System.out.println(A[i]);
}
System.out.println(" ");
}

//prints all the elements smaller than A[j]
public static void printSmaller(double[] A, int j)
{
System.out.println(" ");
for(int i=0; i {
System.out.println(A[i]);
}
System.out.println(" ");
}

//searchs for key
//returns -1 if key not found, index of A[], if found
public static int linearSearch(double[] A, int key)
{
for(int i = 0; i {
if(A[i] == key)
return i;
}
return -1;
}



//main function
public static void main(String[] args)
{
double[] A = new double [10];
Scanner scn = new Scanner(System.in);
int key;

System.out.println(" ");
System.out.println(" ");

for ( int i=0; i {
System.out.println("Enter a number "+i);
A[i] = scn.nextDouble();
}

System.out.println(" ");

selectionSort(A);
printAllSorted(A);

System.out.println(" ");

System.out.println("enter the numer you want to search : ");
key = scn.nextInt();

int j = linearSearch(A,key);

if( j ==-1 )
{
System.out.println(" ");
System.out.println("Key not Found");
}
else
printSmaller(A,j);
}

}

No comments:

Post a Comment