Advertisement
tampurus

25 26 Bubble and Insertion sort

Apr 26th, 2022 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. // Q 25 Bubble sort
  2. public class Main
  3. {
  4.     public static void main(String[] args) {
  5.         int[] arr = {50,4,31,2,-3};
  6.         int temp,flag;
  7.         int n=5; // size of array
  8.         for (int i = 0; i < n - 1; i++)
  9.         {
  10.             flag = 0;
  11.             for (int j = 0; j < n - i - 1; j++)
  12.             {
  13.                 if (arr[j] > arr[j + 1])
  14.                 {
  15.                     temp = arr[j + 1];
  16.                     arr[j + 1] = arr[j];
  17.                     arr[j] = temp;
  18.                     flag = 1;
  19.                 }
  20.             }
  21.             if (flag==0)
  22.                 break;
  23.         }
  24.  
  25.         for (int i = 0; i < n; i++)
  26.         {
  27.             System.out.print(arr[i]+" ");
  28.         }
  29.     }  
  30.  
  31. }
  32. /*
  33. Input   50,4,31,2,-3
  34. Output  -3,2,4,31,50
  35. */
  36.  
  37. Q 26 Insertion sort
  38. public class Main
  39. {
  40.     static void InsertionSort(int arr[],int n)
  41.     {
  42.         for (int i = 1; i < n; ++i) {
  43.             int key = arr[i];
  44.             int j = i - 1;
  45.             while (j >= 0 && arr[j] > key) {
  46.                 arr[j + 1] = arr[j];
  47.                 j = j - 1;
  48.             }
  49.             arr[j + 1] = key;
  50.         }
  51.     }
  52.     public static void main(String[] args) {
  53.         int[] arr = {5,4,3,2,1};
  54.         int n=5; // size of array
  55.        
  56.         InsertionSort(arr,n);
  57.         for (int i = 0; i < n; i++)
  58.         {
  59.             System.out.print(arr[i]+" ");
  60.         }
  61.     }  
  62.  
  63. }
  64. /*
  65. Input 5,4,3,2,1
  66. Output 1 2 3 4 5
  67. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement