Bubble sort in JAVA programming


  1.  
  2.  
  3. import java.util.Scanner;
  4.  
  5.  
  6. public class BubbleSort {
  7.  
  8.  
  9. public static void main(String[] args) {
  10.  
  11. Scanner myScanner=new Scanner(System.in);
  12.  
  13. int n;
  14.  
  15. int[] arr=new int[100];
  16.  
  17. System.out.print("Enter the number of elements : ");
  18.  
  19. n=myScanner.nextInt();
  20.  
  21. System.out.print("Enter "+n+ " numbers : ");
  22.  
  23. for (int i = 0; i <n; i++) {
  24.  
  25. arr[i]=myScanner.nextInt();
  26.  
  27. }
  28.  
  29. int temp;
  30.  
  31. for (int i = 0; i < n; i++) {
  32.  
  33. for (int j = i+1; j < n; j++) {
  34.  
  35. if (arr[i]>arr[j]) {
  36.  
  37. temp=arr[i];
  38.  
  39. arr[i]=arr[j];
  40.  
  41. arr[j]=temp;
  42.  
  43. }
  44.  
  45. }
  46.  
  47. }
  48.  
  49. System.out.print("Sorted list are : ");
  50.  
  51. for (int i = 0; i < n; i++) {
  52.  
  53. System.out.print(arr[i]+"\t");
  54.  
  55. }
  56.  
  57. System.out.println();
  58.  
  59. }
  60.  
  61.  
  62. }
  63.  
  64. //Enter the number of elements : 5
  65.  
  66. //Enter 5 numbers : 8 34 23 424241 1
  67.  
  68. //Sorted list are : 1 8 23 34 424241

No comments:

Post a Comment