KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > db4o > foundation > Algorithms4


1 /* Copyright (C) 2004 - 2006 db4objects Inc. http://www.db4o.com
2
3 This file is part of the db4o open source object database.
4
5 db4o is free software; you can redistribute it and/or modify it under
6 the terms of version 2 of the GNU General Public License as published
7 by the Free Software Foundation and as clarified by db4objects' GPL
8 interpretation policy, available at
9 http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
10 Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
11 Suite 350, San Mateo, CA 94403, USA.
12
13 db4o is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */

21 package com.db4o.foundation;
22
23
24 /**
25  * @exclude
26  */

27 public class Algorithms4 {
28     
29     private static class Range {
30         int _from;
31         int _to;
32
33         public Range(int from, int to) {
34             _from = from;
35             _to = to;
36         }
37     }
38     
39     public static void qsort(QuickSortable4 sortable) {
40         Stack4 stack=new Stack4();
41         addRange(stack, 0, sortable.size()-1);
42         qsort(sortable,stack);
43     }
44
45     private static void qsort(QuickSortable4 sortable, Stack4 stack) {
46         while(!stack.isEmpty()) {
47             Range range=(Range)stack.peek();
48             stack.pop();
49             int from=range._from;
50             int to=range._to;
51             int pivot = to;
52             int left = from;
53             int right = to;
54             while (left<right) {
55                 while (left<right && sortable.compare(left,pivot)<0) {
56                     left++;
57                 }
58                 while(left<right && sortable.compare(right,pivot)>=0) {
59                     right--;
60                 }
61                 swap(sortable, left, right);
62             }
63             swap(sortable, to, right);
64             addRange(stack, from, right-1);
65             addRange(stack, right+1, to);
66         }
67     }
68
69     private static void addRange(Stack4 stack,int from,int to) {
70         if (to-from < 1) {
71             return;
72         }
73         stack.push(new Range(from,to));
74     }
75     
76     private static void swap(QuickSortable4 sortable, int left, int right) {
77         if (left == right) {
78             return;
79         }
80         sortable.swap(left, right);
81     }
82
83 }
84
Popular Tags