Quicksort for strings in Java 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: how to quicksort a string array in java
package com.javacodegeeks.sorting.quicksort;
public class QuicksortStringExample {
private static String []a;
public static void main(String[] args) {
a = new String[]{"X","E","C","A"};
printArray();
sort();
System.out.println("");
printArray();
}
public static void sort(){
int left = 0;
int right = a.length-1;
quickSort(left, right);
}
private static void quickSort(int left,int right){
if(left >= right)
return;
String pivot = getMedian(left, right);
int partition = partition(left, right, pivot);
quickSort(0, partition-1);
quickSort(partition+1, right);
}
private static int partition(int left,int right,String pivot){
int leftCursor = left-1;
int rightCursor = right;
while(leftCursor < rightCursor){
while(((Comparable<String>)a[++leftCursor]).compareTo(pivot) < 0);
while(rightCursor > 0 && ((Comparable<String>)a[--rightCursor]).compareTo(pivot) > 0);
if(leftCursor >= rightCursor){
break;
}else{
swap(leftCursor, rightCursor);
}
}
swap(leftCursor, right);
return leftCursor;
}
public static String getMedian(int left,int right){
int center = (left+right)/2;
if(((Comparable<String>)a[left]).compareTo(a[center]) > 0)
swap(left,center);
if(((Comparable<String>)a[left]).compareTo(a[right]) > 0)
swap(left, right);
if(((Comparable<String>)a[center]).compareTo(a[right]) > 0)
swap(center, right);
swap(center, right);
return a[right];
}
public static void swap(int left,int right){
String temp = a[left];
a[left] = a[right];
a[right] = temp;
}
public static void printArray(){
for(String i : a){
System.out.print(i+" ");
}
}
}