Eduardo J. Nogueras
enogueras@aol.com
I would like to know a good sorting algorithm for
a Vector in the Vector class?
Morten
c960901@student.dtu.dk
What kind of objects does your Vector contain? I've made
the following two implementations of quicksort (nlgn),
the first sorts an array of strings in increasing order,
the next an array of integers.
Morten
import java.io.*
import java.text.*
import java.util.*
class qSortStrings
{
public String A1[]
static boolean DEBUG = false
static int LENGTH = 20
public Collator sortCollator
public qSortStrings()
{
sortCollator = Collator.getInstance(new Locale("en",
"US"))
A1 = new String[LENGTH]
A1[0] = "fdskjf"
A1[1] = "gDFGsd"
A1[2] = "aaab"
A1[3] = "aaaab"
A1[4] = "Aaab"
A1[5] = "gDvcx"
A1[6] = "rewgd"
A1[7] = "Tvtevz"
A1[8] = "GFDgDsfgds"
A1[9] = "GdgdfsE"
A1[10] = "zxy"
A1[11] = "xyz"
A1[12] = "zzy"
A1[13] = "TtdFDSfds"
A1[14] = "Gwev ava"
A1[15] = "Gwevabba"
A1[16] = "GFDgfs"
A1[17] = "GRgfFD"
A1[18] = "gREgdf"
A1[19] = "fdskjf"
quickSortStrings(A1,0,A1.length-1)
for(int i=0 i<LENGTH i++) System.out.println(A1[i])
}
public void quickSortStrings(String[] A,int p,int r)
{
int q
if(p<r)
{
q = quickPartition(A,p,r)
quickSortStrings(A,p,q)
quickSortStrings(A,q+1,r)
}
}
public int quickPartition(String[] A,int p,int r)
{
String x = A[p]
int i = p-1
int j = r+1
while(true)
{
do {j-- } while(sortCollator.compare(A[j],x)>0)
do {i++ } while(sortCollator.compare(A[i],x)<0)
if(i<j)
{
swap(A,i,j)
}
else {
if(DEBUG) System.out.println("return
j: "+j)
return j }
}
}
private void swap(String a[], int i, int j)
{
String T
T = a[i]
a[i] = a[j]
a[j] = T
}
static public void main(String argv[])
{
qSortStrings qSS = new qSortStrings()
}
}
INTEGER QUICKSORT:
import java.io.*
class qSort
{
public int A1[], A2[]
static boolean DEBUG = false
static int LENGTH = 20
public qSort()
{
A1 = new int[LENGTH]
A2 = new int[LENGTH]
for(int i=0 i<LENGTH i++) A1[i] = A2[i]
= (int)(Math.random()*1000)
quickSort(A1,0,A1.length-1)
for(int i=0 i<LENGTH i++) System.out.println(A1[i]+"
"+A2[i])
}
public void quickSort(int[] A,int p,int r)
{
int q
if(p<r)
{
q = quickPartition(A,p,r)
quickSort(A,p,q)
quickSort(A,q+1,r)
}
}
public int quickPartition(int[] A,int p,int r)
{
int x = A[p]
int i = p-1
int j = r+1
if(DEBUG) System.out.println("x: "+A[p]+" i: "+i+"
j: "+j)
while(true)
{
if(DEBUG) System.out.println("j: "+j)
do {j-- } while(A[j]>x)
if(DEBUG) System.out.println("i: "+i)
do {i++ } while(A[i]<x)
if(DEBUG) System.out.println("i: "+i+"
j: "+j)
if(i<j)
{
swap(A,i,j)
}
else {
if(DEBUG) System.out.println("return
j: "+j)
return j }
}
}
private void swap(int a[], int i, int j)
{
int T
T = a[i]
a[i] = a[j]
a[j] = T
}
static public void main(String argv[])
{
qSort qS = new qSort()
}
}