Monday, 20 January 2014

JAVA : selection sort algorithm.

Selection Sort.

public class BubbleSort{

 static int no_of_iteration;

 public static void main(String args[]) throws NumberFormatException,
   IOException {
  BufferedReader buff = new BufferedReader(new InputStreamReader(
    System.in));
  System.out.println("How many no.s to sort");
  int n = Integer.parseInt(buff.readLine());

  int arr[] = new int[n];
  System.out.println("entered " + n + " elements");
  for (int i = 0; i < n; i++) {

   arr[i] = Integer.parseInt(buff.readLine());

  }
  System.out.println("entered elements are");
  for (int i : arr) {

   System.out.println(i);
  }
  for (int i = 0; i < n - 1; i++) {
   no_of_iteration++;
   for (int j = i + 1; j < (n); j++) {
    no_of_iteration++;
    if (arr[i] < arr[j]) {

     int temp = arr[j];
     arr[j] = arr[i];
     arr[i] = temp;

    }
   }
  }
  System.out.println("sorted elements are");
  for (int i : arr) {

   System.out.println(i);
  }
  System.out.println("total no of iteration" + no_of_iteration);
 }

}

No comments:

Post a Comment