brilliant_moves

BubbleSort.java

Feb 1st, 2013
551
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.59 KB | None | 0 0
  1. import java.util.Scanner;   // for user input
  2.  
  3. public class BubbleSort {
  4.  
  5.     /**
  6.     *   Program:    BubbleSort.java
  7.     *   Purpose:    Sort array using bubblesort routine
  8.     *   Creator:    Chris Clarke
  9.     *   Created:    01.02.2013
  10.     */
  11.  
  12.     public static void main(String[] args) {
  13.         // create scanner object
  14.         Scanner scan = new Scanner(System.in);
  15.         int i, n;
  16.         int[] a;
  17.         System.out.println("Enter the size of the unsorted array: ");
  18.         do {
  19.             try {
  20.                 n = scan.nextInt(); // get user input
  21.             } catch (NumberFormatException e) {
  22.                 System.out.println("Must be integer");
  23.                 return;
  24.             }//end try/catch
  25.             if (n > 100) System.out.println("Must not be more than 100");
  26.             if (n < 2) System.out.println("Must not be less than 2");
  27.         } while (n > 100 || n < 2);
  28.         a = new int[n];
  29.  
  30.         System.out.println("Enter each element of the array: ");
  31.  
  32.         for (i=0; i<n; i++) {
  33.             System.out.print("Enter element "+(i+1)+": ");
  34.             try {
  35.                 a[i] = scan.nextInt();
  36.             } catch (NumberFormatException e) {
  37.                 System.out.println("Must be integer");
  38.                 return;
  39.             }//end try/catch
  40.         }//end for
  41.  
  42.         //sort the array
  43.         a = sort(a);
  44.  
  45.         System.out.println("The sorted array looks like this: ");
  46.         for (i=0; i<n; i++) {
  47.             System.out.print(a[i]+" ");
  48.         }
  49.     }//end main
  50.  
  51.     public static int[] sort(int[] a) {
  52.         // apply bubblesort algorithm to array a
  53.         int i,j,temp;
  54.         int len =a.length;
  55.  
  56.         for (i=0; i<len-1; i++) {
  57.             for (j=0; j<len-1-i; j++) {
  58.                 if (a[j]>a[j+1]) {
  59.                     // swap
  60.                     temp=a[j];
  61.                     a[j]=a[j+1];
  62.                     a[j+1]=temp;
  63.                 }//end if
  64.             }//end for j
  65.         }//end for i
  66.  
  67.         return a;
  68.     }//end sort
  69. }//end class
Advertisement
Add Comment
Please, Sign In to add comment