Advertisement
Guest User

Sorting Program

a guest
Aug 10th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. Driver Class:
  2.  
  3. import java.util.Scanner;
  4. public class sort
  5. {    
  6.     public static void main(String args[])
  7.     {
  8.         Scanner scan = new Scanner(System.in);
  9.  
  10.         System.out.print("Enter number of integers: ");
  11.         int numints = scan.nextInt();
  12.  
  13.         int[] intarray = new int[numints];  
  14.  
  15.         for(int i = 0; i < numints; i++)
  16.         {
  17.             System.out.print("Enter integer " + (i + 1) + ": ");
  18.             intarray[i] = scan.nextInt();
  19.  
  20.         }
  21.  
  22.         System.out.println();
  23.  
  24.         System.out.println("The integers you entered are: ");
  25.         bubblesort.printArray(intarray);
  26.  
  27.         System.out.println();
  28.  
  29.         System.out.println("Your integers sorted in accending order are: ");
  30.         bubblesort.ascending(intarray);
  31.         bubblesort.printArray(intarray);
  32.  
  33.         System.out.println();
  34.  
  35.         System.out.println("Your integers sorted in descending order are: ");
  36.         bubblesort.descending(intarray);
  37.         bubblesort.printArray(intarray);
  38.  
  39.     }
  40. }
  41.  
  42.  
  43. Classes:
  44.  
  45. public class bubblesort
  46. {
  47.     public static void ascending(int[] intarray)
  48.     {
  49.         int i, j, temp;
  50.  
  51.        
  52.         for(i = intarray.length - 1; i > 0; i--)
  53.         {
  54.             for(j = 0; j < i; j++)
  55.             {
  56.                 if(intarray[j] > intarray[j+1])
  57.                 {
  58.                     temp = intarray[j];
  59.                     intarray[j] = intarray[j+1];
  60.                     intarray[j+1] = temp;
  61.                 }
  62.             }
  63.         }
  64.     }
  65.    
  66.     public static void descending(int[] intarray)
  67.     {
  68.         int i, j, temp;
  69.        
  70.         for(i = intarray.length - 1; i > 0; i--)
  71.         {
  72.             for(j = 0; j < i; j++)
  73.             {
  74.                 if(intarray[j] < intarray[j+1])
  75.                 {
  76.                     temp = intarray[j];
  77.                     intarray[j] = intarray[j+1];
  78.                     intarray[j+1] = temp;
  79.                 }
  80.             }
  81.         }
  82.     }
  83.    
  84.     public static void printArray(int[] intarray)
  85.     {
  86.         for(int i = 0; i < intarray.length; i++)
  87.         {
  88.             System.out.println(intarray[i]);
  89.         }
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement