Quick sort recursion
this is my version of quick sort
i cant seem to figure out how to make it a recursive code
any line of code that helps me do this, along with an explanation of why it works will be welcomed. Recursion is just too hard to picture inside my head
public static String[] quickSort (String[] A, int start, int end){
//if size is 1 return
if (A.length < 2 ) return A;
int pivotIndex = start;
//do the partition
for (int i=pivotIndex+1; i<end; i++){
if (compareStrings(A,A[pivotIndex])){
swapString(A, pivotIndex+1, i);
swapString(A, pivotIndex, pivotIndex+1);
pivotIndex++;
return A;
when i take the return type out of the method, aka i make it void, and i write those two lines i am getting a runtime error
this is the code
public static void quickSort (String[] A, int start, int end){
//if size is 1 return
if (A.length < 2 ) return;
int pivotIndex = start;
//do the partition
for (int i=pivotIndex+1; i<end; i++){
if (compareStrings(A,A[pivotIndex])){
swapString(A, pivotIndex+1, i);
swapString(A, pivotIndex, pivotIndex+1);
pivotIndex++;
quickSort(A, start, pivotIndex);
quickSort(A, pivotIndex+1, end);
this is how i call it
String[] data2 = new String[10];
data2[0]= "5";
data2[1]= "2";
data2[2]= "9";
data2[3]= "7";
data2[4]="8";
data2[5]= "0";
data2[6]="3";
data2[7]= "1";
data2[8]="4";
data2[9]= "6";
quickSort(data2);
System.out.println("");
System.out.println("============================================");
System.out.println("");
for (int i=0; i < data.length; i++) {System.out.println(data2);}
Similar Messages
-
Quick sorting of Portrait or Landscape images?
When outputting for a web site, I find I need to apply different sizes to Portrait images than to Landscape ones.
Does anyone know how to quickly sort images into these two types?
Thanks in advanceGo to Library View. Show the Filter bar at the top, and select "Metadata". Then set one of the search fields from the drop down box to Aspect Ratio. You will have the choice of Portrait and Landscape. Click whichever one you wish to show.
Lou -
Quick-Sort Algorithm HELP !!!
hi there, I wrote a method to sort an 2D-Vector. I used the Bubble-Algorithm.
Here the code:
Vector == [Micky, Niko, Tete] ; [Lilo, Eli, Micha];
public static void bubbleSort( Vector v,
int sortColumn,
boolean ascending )
int i = 0,
j = 0,
length = v.size();
Vector tmp1,
tmp2;
for (i = 0; i < (length - 1); i++)
for (j = i+1; j < length; j++)
tmp1 = (Vector) v.elementAt(i);
tmp2 = (Vector) v.elementAt(j);
if (SortUtil.isGreaterThan(tmp1.elementAt(sortColumn), tmp2.elementAt(sortColumn)) > 0)
// swap
SortUtil.swap2D(v, i, j);
public class SortUtil
public static int isGreaterThan(Object obj1, Object2)
// String
if ( (obj1 instanceof String) && (obj2 instanceof String) )
return ( ((String) obj1).compareTo((String) obj2) );
public static void swap2D(Vector v, int i)
Vector tmp = (Vector) v.elementAt(i);
v.setElementAt((Vector) v.elementAt(i+1), i);
v.setElementAt(tmp, i+1);
I want now to write a method to use the quick-sort-algorithm.
How can I do this.
thanks a lot.
micky z.Hi
You can use java.util.Arrays.sort() method to sort an array of data in quick sort algo. May be you will have to use a n array insted of the Vector.
Use vector.toArray() method to get an array from the vector.
But if you want to use a dynamically resizing container like the Vector, use a java.util.LinkedList insted of the Vector and use Collections.sort() method
Good luck. -
Quick Sort Functionality in PE 4
When I create a slideshow using Elements 6, I can at any time do a quick sort without losing any of my transition or other settings. Is the same functionality available in Premiere 4?
What are you trying to sort, Peet?
You can sort the files in the Project media panel in a number of ways. (Just click on the head of the column -- and you can add colums for various other metadata.)
You can also open the Premiere Elements Organizer and sort your files with a variety of criteria there.
Or are you talking about sorting the slideshow itself? That's something you can't do as easily in Premiere Elements.
On the other hand, that's why the Photoshop Elements slideshow creator exports the finished slideshow to Premiere Elements -- so you can use the best features of each program! -
Can someone help me why this quick sort doesn't work
public class QuickSortII {
static void sort(int a[], int lo0, int hi0) {
int lo = lo0;
int hi = hi0;
if (lo >= hi) {
return;
int mid = a[(lo + hi) / 2];
while (lo < hi) {
while (lo<hi && a[lo] < mid) {
lo++;
while (lo<hi && a[hi] >= mid) {
hi--;
if (lo < hi) {
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
sort(a, lo0, lo);
sort(a, lo == lo0 ? lo+1 : lo, hi0);
static void sort(int a[]) {
sort(a, 0, a.length-1);
static public void main(String[] args) {
int a[] = new int[20];
a[0] = 18;
a[1] = 11;
a[2] = 12;
a[3] = 4;
a[4] = 20;
a[5] = 5;
a[6] = 1;
a[7] = 3;
a[8] = 16;
a[9] = 8;
a[10] = 7;
a[11] = 17;
a[12] = 9;
a[13] = 6;
a[14] = 19;
a[15] = 2;
a[16] = 13;
a[17] = 15;
a[18] = 10;
a[19] = 14;
sort(a);
for (int j = 0; j < 20; j++) {
System.out.print(a[j] + " ");
}it doesn't sort the listit doesn't sort the list Please explain why you think it should. Doing so will help you understand the code.
~ -
In previous versions of Mail, you've always been able to do quick sorting of messages with the To/From, Subject, Date Received tabs at the top of the message lists. I don't use the Conversation view, preferring instead the Classic view. When selecting/highlighting a message in a list, the message would resort themselves if you clicked on any of the header tabs. However, now, this doesn't happen. It will resort the whole list and you lose your target message.
Note, that searching for messages or the "show related messages" function in the View pull-down menu is far less useful and convenient to scan messages. There's no more list.
Does anyone have any insights into how to get this feature back? Or why such a simple and useful feature would no longer be present.Frontage,
YES. Isn't it silly. Somehow, software companies feel an over arching need to offer new versions & so often, THEY MESS THEM UP! If only we could easily go back to the previous ones.
However, in this case, there is a solution- Like you, I was trying to figure out what Old Toad was saying & where on the screen his pic came from. I was clicking around the upper left corner of the screen, on the flag icon, on the mailboxes & perhaps other things. Something I did restored the feature, so that when sorted, the message used as the sort key remains selected. I quit Mail & restarted & it still works.
So there is a solution. (I just wish I could say what it was.) -
I need to sort an array of strings based on the number in each string.
Basically, I have a directory of files that all have the same name but each with a different number on the end.
example: image 1.jpg, image 2.jpg, etc.
When I use the List Directory function that returns an array of strings containing the file names in the directory, they don't come out in a 1, 2, 3, order like they appear in the directory. It sorts them character by character so that they come out like: 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22 etc.
Is there a simple way of sorting this array of strings with the file names (as above) so that they are in numerical order?It's a while since this thread was started, but I am sure others will have use for this so here goes:
The in-built array sort function sorts the strings the same way DOS and Windows do. Microsoft has fixed this in the Explorer that comes with XP, however the rest of the OS(s) still sorts the old way.
The attached "AlphaLogical String Array Sort" VIs will sort strings arrays the same way as the new XP Explorer. There are three different implementations of the sorting, one based on the Insertion sort algorithm, a Quick Sort based on recursive calls (the most elegant way, but unfortunately LabVIEW has too much overhead when doing recursive calls so this is actually a very slow alternative) and finally the fastest; a stack based Quick Sort. There is also a test VI that will show you how the different implementations perform.
I had not used recursive calls in LV much until I made the attached quick sort and was a bit disappointed by the fact that it is so slow, but it's a good learning example...The ability to do recursive calls this way was introduced in LV7 I believe...There is an example here on the zone that shows how you can calulate a factorial by using recursive calls, however - unlike for the quick sort (normally) - recursive calls are actually not the optimal solution for that calculation.
Message Edited by Mads on 09-13-2005 02:30 AM
MTO
Attachments:
AlphaLogical Sorting.zip 142 KB -
Infinite recursion - base case ignored and stack overflowed
Hi, I've been having this logic error for 2 days, and I cannot fix it. Right now, I can barely see anything because I was looking at computer screen for 10 hours. The code I'm writing is a program that allows the user to play a list of MP3 files in a folder. Among commands we have to make, we have to sort the list according to authors, dates, and titles as desired by the user. This specific problem I'm having is from the sorting method. We have to use quick sort, and through the help of textbook and online, I was able to write the code as follows. The problem is, I'm having an infinite recursion. The base case I wrote and if else statement are completely ignored and the method keeps calling itself. Perhaps, return statement is not how you are supposed to end a recurssive method? I have no idea. Any help will be appreciated. Thank you in advance.
public void sort (Comparator<MP3File> comp) {
System.out.println("first: " + first + "last: " + last);
quickSort(first, last, comp);
System.out.println("done");
return;
public void quickSort (int left, int right, Comparator<MP3File> comp) {
int leftBound= left;
int rightBound= right;
System.out.println("before sorting: left - " + left + " right - " + right);
if (left>=right) {
return;
if ( ( left < 0 ) || ( left >= listOfMP3.length ) ||
( right < 0 ) || ( right >= listOfMP3.length ) ) {
throw new IndexOutOfBoundsException();
if (right-left>=1) {
System.out.println("difference between right and left: " + (right-left));
MP3File pivot = listOfMP3[left];
while (rightBound>leftBound)
while (comp.compare(listOfMP3[leftBound], pivot)<= 0 && leftBound<=right &&rightBound>leftBound) {
leftBound++;
System.out.println("leftBound " + leftBound);
while (comp.compare(listOfMP3[rightBound], pivot)>0 && rightBound>=left &&rightBound>=leftBound) {
rightBound--;
System.out.println("rightBound " + rightBound);
if (rightBound>leftBound) {
swap (leftBound,rightBound);
swap(left, rightBound);
System.out.println("swapped");
System.out.println("calling left sorting");
quickSort(left, rightBound-1, comp);
System.out.println("calling right sorting");
quickSort(rightBound+1, right, comp);
else {
System.out.println("wtf");
return;
System.out.println("error");
return;
public void swap(int index1, int index2) {
MP3File temp = listOfMP3[index1];
listOfMP3[index1] = listOfMP3[index2];
listOfMP3[index2] = temp;
}naranja wrote:
Enlighten me further please? How do you use sort method using collections?[http://www.google.com/search?q=java+sort+tutorial] -
Does anyone have a program that contains a way of analysing the speed at which data from a file is sorted, implemented using teh following algorithms - bubble sort, shell sort and Quick Sort. The file with the elements to be sorted is a simple text file and it has six figure numbers in one single coloumn.
Cheers
GrantDoes anyone have a program that contains a way of
analysing the speed at which data from a file is
sortedSorts are typically analyzed mathematically, based on the number of loops, recursions, whatever. From memory, and I'm sure someone will correct me if/where I'm wrong:
Bubble = O(n^2) -- ie, for a set of N items, it performs the
innermost code N*N
Shell = O(N*log2(N)) -- I don't think this is quite right, but
Shell is one of the faster sorts around
Quick = varies -- on random input, I think it's N*log2(N),
but on already-sorted input it is N*N -
I'm trying to sort a set of 4 lists that depend on each other. I'm using a bubble-sort to do this. I sort one list and when I need to swap items I also swap the corresponding items in the other three lists to keep them all synced.
So far I've only done this using a set of short lists. I've calculated that in order to sort the entire data-set using my bubble-sort will require about 20hrs (roughly 8000 items in each list).
I've looked into Database Events but it doesn't seem to have a sort function. I found a quick-sort routine on the web, but the code lacks comments and thus makes no sense to me.
Anybody know of a faster way to sort?
Message was edited by: MausyHello
You may try a flavour of merge sort handler, which is stable (i.e. preserves original order of items with the same key) and has N * log N complexity in both average and the worst case.
(Quick sort is not stable and has N * N complexity in the worst case.)
Notes about the script.
In brief,
0) given a list of keys (= kk) and a list of values (= aa);
1) create a list of indices (= ii) to identify each value in original aa;
2) transpose {kk, ii} and build a list (= xx) of which element is {kk's item j, ii's item j} for i from 1 to count kk;
3) sort xx by its element's first item;
4) transpose xx and get sorted kk and sorted ii by key;
5) bulid sorted value list (= aa1) by extracting items from aa by using sorted indices sequentially.
(You can build sorted value list from other value list by using the same sorted indices sequentialy)
There're three essential handlers: cmp(), msort() and transpose().
The cmp() is comparator for msort() and cmp(x, y) returns true iff element x and y are out of order.
The msort() is non-recursive merge sort handler. (I made it non-recursive to avoid stack-overflow in AppleScript)
The transpose() is 2d-array transposer.
Hope you get the picture.
Good luck,
H
--SCRIPT
test()
on test()
script o
property kk : {} -- key list
property ii : {} -- index list
property aa : {} -- value list
property aa1 : {} -- value list sorted by key
set h to 100 -- test list size
-- make key list
repeat with i from 1 to h
set end of my kk to random number from 0 to (h div 2)
end repeat
set kk0 to kk's contents -- save original key list
-- make index list
repeat with i from 1 to count my kk
set end of my ii to i
end repeat
-- make value list
repeat with i from 1 to count my kk
set end of my aa to "a" & i
end repeat
-- sort list of (key & index) pair by key
set xx to transpose({kk, ii}) -- transpose
msort(xx, my cmp) -- sort
set {kk, ii} to transpose(xx) -- transpose back
-- retrieve values by sorted indices
repeat with i in my ii
set end of my aa1 to my aa's item i
end repeat
return {original_keys:kk0, sorted_keys:kk, sortedindices_bykey:ii, sortedvalues_bykey:aa1}
end script
tell o to run
end test
on cmp(x, y) -- comparator for msort handler
(* sort in ascending order of 1st item of list element *)
return x's item 1 > y's item 1
end cmp
on cmp(y, x) -- comparator for msort handler
(* sort in descending order of 1st item of list element *)
return x's item 1 > y's item 1
end cmp
on msort(aa, cmp_) -- v1.2f1
Basic non-recursive merge sort handler
having list sorted in place in ascending order.
list aa : list to be sorted in place
handler cmp_ : comparator
* cmp(x, y) must return true iff list element x and y are out of order.
script o
property xx : aa -- to be sorted in place
property xxl : count my xx
property yy : {}
property cmp : cmp_
on merge(p, q, r)
property xx: source list -- [*1]
integer p, q, r : absolute indices to specify range to be merged such that
xx's items p thru r is the target range,
xx's items p thru (q-1) is the first sublist already sorted (in ascending order) and
xx's items q thru r is the second sublist already sorted (in ascending order).
(p < q <= r)
Notes
[1] It assumes that xx[p, q-1] and xx[q, r] have been already sorted (p < q <= r).
Also xx is modified in place.
local i, j, k, xp, xr, yi, yj, ix, jx
if r - p = 1 then
set xp to my xx's item p
set xr to my xx's item r
if my cmp(xp, xr) then
set my xx's item p to xr
set my xx's item r to xp
end if
return -- exit
end if
if my cmp(my xx's item (q - 1), my xx's item q) then
else -- xx[p, q-1] & xx[q, r] are already sorted
return
end if
set yy to my xx's items p thru r -- working copy for comparison
set ix to q - p
set jx to r - p + 1
set i to 1
set j to q - p + 1
set k to p
set yi to my yy's item i
set yj to my yy's item j
repeat
if my cmp(yi, yj) then
set my xx's item k to yj
set j to j + 1
set k to k + 1
if j > jx then
set my xx's item k to yi
set i to i + 1
set k to k + 1
repeat until k > r
set my xx's item k to my yy's item i
set i to i + 1
set k to k + 1
end repeat
return
end if
set yj to my yy's item j
else
set my xx's item k to yi
set i to i + 1
set k to k + 1
if i > ix then
set my xx's item k to yj
set j to j + 1
set k to k + 1
repeat until k > r
set my xx's item k to my yy's item j
set j to j + 1
set k to k + 1
end repeat
return
end if
set yi to my yy's item i
end if
end repeat
end merge
on cmp(x, y)
(* default comparator for sort in ascending order (used if cmp_ = {}) *)
return x > y
end cmp
local d, i, j
if xxl ≤ 1 then return
if cmp_ = {} then set my cmp to cmp
set d to 2
repeat until d > xxl
repeat with i from 1 to (xxl - d + 1) by d
my merge(i, i + d div 2, i + d - 1)
end repeat
set i to i + d
set j to i + d div 2
if j ≤ xxl then my merge(i, j, xxl)
set d to d * 2
end repeat
if i ≤ xxl then my merge(1, i, xxl)
end script
tell o to run
end msort
on transpose(dd)
list dd: two dimentional array. e.g. {{11, 12}, {21, 22}, {31, 32}}
return list: transposed array. e.g. {{11, 21, 31}, {12, 22, 32}}
extra e.g.
{{1, 2, 3}} -> {{1}, {2}, {3}} [or {1, 2, 3} -> {{1, 2, 3}} -> {{1}, {2}, {3}}],
{{1}, {2}, {3}} -> {{1, 2, 3}}
script o
property aa : dd
property xx : {}
property yy : {}
local n
if my aa is {} then return {}
if my aa's item 1's class is not list then set my aa to {my aa} -- as (1,n) array
set n to my aa's item 1's length
repeat with a in my aa
if (count a) is not n then error "lists' lengths mismatch" number 8008
end repeat
repeat with i from 1 to n
set my xx to {}
repeat with a in my aa
set end of my xx to a's item i
end repeat
set end of my yy to my xx
end repeat
return my yy's contents
end script
tell o to run
end transpose
--END OF SCRIPT
Message was edited by: Hiroto -
Sort messages in Mavericks Mail
Hello,
I upgraded from Snow Leopard directly to Mavericks. With respect to the previous version of Mail, I find the following functions not easily accessed as before. In a work environment this means wasting more time to do the same thing.
1) There is no possibility to quickly "sort" messages like before. Previously it was very quick to do it by selecting date, addressee, etc.
I can do this by selecting "Classic layout" but in that case I lose the side preview panel which I have now, and the old WideMail plugin doesn't work anymore.
2) When you write a new message there is no "save draft" button anymore.
3) When you make a search in Mail there is a lot of information coming out, which are not needed.
ThanksJean...hi
like you I am going from Snow Leopard to Mavericks.....a whole new world...Mail for me is the programme with the steepest learning curve .
can help you with this perhaps:
---sort: note above the inbox panel/window thare are sorting functions:
click the tiny arrow and for sorting options.
----also when searching, choose options from drop down.
---when switching to classic view: the preview panel is below, like it was before...
---save draft: cmd s
----check out the mail preference...Yes, I have spent so much time at work figuring out the new way. also youtube tutorials on Lion and maybe Mt. Lion give instructions on Mails new look.
good luck....i feel your pain, brother.... -
So I wanted to make an automator that watches a folder and when a file is added it should quickly sort it into one of my other foldrs based on its extension.so if its a pdf it should go into folder "pdf".
I thought I could be smart and instead of making a workflow for each filetype I can have automator find the extension and move the file into that extension folder.
i thought I could call an apple script that will return the extension name.
Im having trouble it wont work passed the applscript step
....anyone know what I can do?
i pass the file into my applescript:
on run {input, var1}
set var1 to (get name extension of file "input")
return var1
end run
and it says it cant get input?
Message was edited by: shamguy4In the *Run AppleScript* action's run handler statement:on run {input, parameters}
the input parameter variable is a list of the items passed to the action, and the parameters parameter variable is a list of the parameters of the *Run AppleScript* action itself (the action's user interface - e.g. the source text of the script, if it ignores input, etc). Typically you just loop through the input list:on run {input, parameters}
repeat with anItem in the input
-- do something with the item
end repeat
return input -- or return the results of your script (for the next action)
end run -
Using 'P & X' to sort images in LRM 5
I have just downloaded a batch of images into LRM 5 - with earlier versions in 'Library' I have been able to go quickly through all the images using P or X.
I have just found that in 5 when P or X are used, the image either shoots to the start or the end of the group. So to move on to the next image you have to sort back to where you were previously - this is a real PAIN and makes a mockery of Quick Sorting'
Why is this happening - is it me or the sortware?!!
Message was edited by: Bella 2 -
I am using a PC with Windows 7 - upgraded from LRM 4 - at the moment everything else seem to be working OK!Thank you for that!
I have been with LRM since version 1 and have never come across this before - certainly never knowingly set 'Capture time' - but it has worked!
Thanks again -
XML Form - How to sort on Created -
Hello Techies,
I have made a custom XML news list with the forms builder.
I want to sort the news items by creation date.
I tried putting "/Properties/default:created" in the sort field of the showlist view. But without result.
Does anybody how to quickly sort new items by creation date and time?
Best Regards,
Defour FrederikIndeed the sorting works both using the collection renderer or the sort in the form. Only trouble the sort does not work properly.
We use dateformat DD/MM/YYYY. I have a few items and these are sorted like this ( these are create dates )
28/06/2005 - 23/09/2004 - 23/05/2005 - 15/06/2005 - 14/06/2005
Seems to me that the sort does not see dates but numbers
28062005> 23092004> 23052005 etc....
I already opened a message but I keep this forum open.
I you have a clue, please advice.
Thanks -
Hello,
I am trying to create a programme where a user has to input 8 integers into an array, and it quicksorts them using an array.
I have the QuickSort programme ready which is:
* 8th of September 2008
* Let a user input different numbers, and quick sort them automatically
public class QuickSort
public void quickS(int start, int finish, int [] array)
int [] quickS = {a, b, c, d, e, 8, 1};
int pivot, left, right, temp;
left = start;
right = finish;
pivot = array[ (left+right)/2];
while (right > left)
while (array[ left] < pivot)
left = left + 1;
while (pivot < array[ right])
right = right - 1;
if (left <= right)
temp = array[ left];
array[ left] = array[ right];
array[ right] = temp;
left = left + 1;
right = right - 1;
if (start < right) quickS(start, right, array);
if (left < finish) quickS(left, finish, array);
}Now I am trying to create another class, which lets a user input integers into an array of size 8. But how do I do that? I've tried several ways and it is not working.
Thank you,I have 3 files, one called SavitchInt which reads entries from Keyboard, other QuickSort which is posted above, and one called QuickSortMain which is the main class.
The code is below:
public class QuickSortMain
public static void main (String [] args)
int[] quickS = new int[8];
for (int i = 0; i < 8; i++)
int num = SavitchIn.readLineInt();
quickS[i] = num;
System.out.println(quickS);
}Now somewhere here, I must send off the keyboard inputs to QuickSort
How should I do that?
Thanks
Maybe you are looking for
-
Mac OSX 10.6.4 compatibility
I have searched this and other forums to try and determine why Adobe does not offer a Reader-download for Intel OSX v 10.6.4. The most recent update is suggested for Intel OSX 10.5.6 - 10.6.3, and there the support ends, supposedly. I know Apple beli
-
How can I eliminate duplicate Batch Numbers?
SBO allows serial numbers to be unique, but not batch numbers. The system allows the same batch number to be used for a different part. I have a medical company that requires unique Batch numbers accross the board, regardless of part number. Any sugg
-
MacBookPro 13' connected to TV using VGA
Hey. I have a MacBookPro 13 and a "old" Finlux 28' screen and I want to connect them together so that I can watch movies on the tv instead of the small 13'. From before I had a VGA to mini-displayport witch I never use. Now I tought that I should use
-
Why has my iPad been freezing and slow since after I installed the iOS 8.0
ipad freezing after installing new operating system
-
Transparency and masks???
how do i erase lower layers seen through the transparent areas of an upper layer - i only want to mask or hide or erase the areas of a lower layer seen through the transparent areas of an upper layer. sorry if this is easy - i'm a bit of a newbie.