quick sort method java String code example
Example 1: is it possible to quick sort a string in java
public class StringQuickSort {
String names[];
int length;
public static void main(String[] args) {
StringQuickSort sorter = new StringQuickSort();
String words[] = {"zz", "aa", "cc", "hh", "bb", "ee", "ll"};
sorter.sort(words);
for (String i : words) {
System.out.print(i);
System.out.print(" ");
}
}
void sort(String array[]) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
}
Example 2: quick sort code in java
import java.util.*;
class QuickSort {
int partition(int intArray[], int low, int high) {
int pi = intArray[high];
int i = (low-1);
for (int j=low; j<high; j++) {
if (intArray[j] <= pi) {
i++;
int temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
int temp = intArray[i+1];
intArray[i+1] = intArray[high];
intArray[high] = temp;
return i+1;
}
void quick_sort(int intArray[], int low, int high) {
if (low < high) {
int pi = partition(intArray, low, high);
quick_sort(intArray, low, pi-1);
quick_sort(intArray, pi+1, high);
}
}
}
class QUICK_SORT{
public static void main(String args[]) {
int intArray[] = {3,2,1,6,5,4};
int n = intArray.length;
System.out.println("Original Array: " + Arrays.toString(intArray));
QuickSort obj = new QuickSort();
obj.quick_sort(intArray, 0, n-1);
System.out.println("\nSorted Array: " + Arrays.toString(intArray));
}
}