ADVERTISEMENT
ADVERTISEMENT

Java program to sort an array in ascending order using quicksort

Given/input an array, we have to sort an array in ascending order using quicksort.
Submitted by Nidhi, on March 14, 2022

Problem Solution:

In this program, we will create an array of integers then we will sort array elements in ascending order using quicksort.

Program/Source Code:

The source code to sort an array in ascending order using quicksort is given below. The given program is compiled and executed successfully.

// Java program to sort an array in ascending order 
// using quicksort

import java.util.Scanner;

public class Main {
  static void QuickSort(int arr[], int first, int last) {
    int pivot = 0;
    int temp = 0;
    int i = 0;
    int j = 0;

    if (first < last) {
      pivot = first;
      i = first;
      j = last;

      while (i < j) {
        while (arr[i] <= arr[pivot] && i < last) {
          i = i + 1;
        }
        while (arr[j] > arr[pivot]) {
          j = j - 1;
        }

        if (i < j) {
          temp = arr[i];
          arr[i] = arr[j];
          arr[j] = temp;
        }
      }

      temp = arr[pivot];
      arr[pivot] = arr[j];
      arr[j] = temp;

      QuickSort(arr, first, j - 1);
      QuickSort(arr, j + 1, last);
    }
  }

  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int i = 0;
    int j = 0;
    int t = 0;

    int arr[] = {14, 49, 79, 87, 78};

    QuickSort(arr, 0, arr.length - 1);

    System.out.println("Sorted Array in ascending order: ");
    i = 0;
    while (i < 5) {
      System.out.print(arr[i] + " ");
      i = i + 1;
    }
  }
}

Output:

Sorted Array in ascending order: 
14 49 78 79 87

Explanation:

In the above program, we imported the java.util.Scanner package to read the variable's value from the user. And, created a public class Main. It contains two static methods QuickSort() and main().

The QuickSort() is a recursive method, which is used to sort an array in ascending order.

The main() method is an entry point for the program. Here, we created an array. Then we used QuickSort() method to sort the array elements in ascending order using the quick sort technique and printed the updated array.

Java Array Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.