Home Sorting Tests
Post
Cancel

Sorting Tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Sort {
  public void insertion(int arr[]) {
    int n = arr.length;
    for (int i = 1; i < n; i++) {
      int x = arr[i];
      int j = i - 1;
  
      while (j >= 0 && arr[j] > x) {
        arr[j + 1] = arr[j];
        j = j - 1;
      }
      arr[j + 1] = x;
    }
  }

  static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 12, 11, 13, 5, 6 };

        printArray(arr);

        Sort ob = new Sort();
        ob.insertion(arr);
 
        printArray(arr);
    }
}

Sort.main(null);
1
2
12 11 13 5 6 
5 6 11 12 13 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class GFG {
     
  // An optimized version of Bubble Sort
  static void bubbleSort(int arr[], int n)
  {
      int i, j, temp;
      boolean swapped;
      for (i = 0; i < n - 1; i++) {
          swapped = false;
          for (j = 0; j < n - i - 1; j++) {
              if (arr[j] > arr[j + 1]) {
                   
                  // Swap arr[j] and arr[j+1]
                  temp = arr[j];
                  arr[j] = arr[j + 1];
                  arr[j + 1] = temp;
                  swapped = true;
              }
          }

          // If no two elements were
          // swapped by inner loop, then break
          if (swapped == false)
              break;
      }
  }

  // Function to print an array
  static void printArray(int arr[], int size)
  {
      int i;
      for (i = 0; i < size; i++)
          System.out.print(arr[i] + " ");
      System.out.println();
  }

  // Driver program
  public static void main(String args[])
  {
      int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
      int n = arr.length;
      bubbleSort(arr, n);
      System.out.println("Sorted array: ");
      printArray(arr, n);
  }
}

GFG.main(null);
1
2
Sorted array: 
11 12 22 25 34 64 90 
This post is licensed under CC BY 4.0 by the author.

Plan 14

Plan 15