Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- public class BubbleSort {
- /**
- * Program: BubbleSort.java
- * Purpose: Sort array using bubblesort routine
- * Creator: Chris Clarke
- * Created: 01.02.2013
- */
- public static void main(String[] args) {
- // create scanner object
- Scanner scan = new Scanner(System.in);
- int i, n;
- int[] a;
- System.out.println("Enter the size of the unsorted array: ");
- do {
- try {
- n = scan.nextInt(); // get user input
- } catch (NumberFormatException e) {
- System.out.println("Must be integer");
- return;
- }//end try/catch
- if (n > 100) System.out.println("Must not be more than 100");
- if (n < 2) System.out.println("Must not be less than 2");
- } while (n > 100 || n < 2);
- a = new int[n];
- System.out.println("Enter each element of the array: ");
- for (i=0; i<n; i++) {
- System.out.print("Enter element "+(i+1)+": ");
- try {
- a[i] = scan.nextInt();
- } catch (NumberFormatException e) {
- System.out.println("Must be integer");
- return;
- }//end try/catch
- }//end for
- //sort the array
- a = sort(a);
- System.out.println("The sorted array looks like this: ");
- for (i=0; i<n; i++) {
- System.out.print(a[i]+" ");
- }
- }//end main
- public static int[] sort(int[] a) {
- // apply bubblesort algorithm to array a
- int i,j,temp;
- int len =a.length;
- for (i=0; i<len-1; i++) {
- for (j=0; j<len-1-i; j++) {
- if (a[j]>a[j+1]) {
- // swap
- temp=a[j];
- a[j]=a[j+1];
- a[j+1]=temp;
- }//end if
- }//end for j
- }//end for i
- return a;
- }//end sort
- }//end class
Advertisement
Add Comment
Please, Sign In to add comment