Download code

Jump to: navigation, search

Back to Bubble_sort_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

BubbleSortExample.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Bubble_sort_(Java)?oldid=19026
14 */
15 
16 
17 import java.util.Random;
18 
19 class BubbleSortExample
20 {
21     public static void bubble_sort(int[] array)
22     {
23     	int right_border = array.length - 1;
24 
25     	do
26     	{
27     		int last_exchange = 0;
28 
29     		for (int i = 0; i < right_border; i++)
30     		{
31     			if (array[i] > array[i + 1])
32     			{
33     				int temp = array[i];
34     				array[i] = array[i + 1];
35     				array[i + 1] = temp;
36 
37     				last_exchange = i;
38     			}
39     		}
40 
41     		right_border = last_exchange;
42     	}
43     	while (right_border > 0);
44     }
45 
46 
47     public static <T extends Comparable<? super T>> void bubble_sort_generic(T[] array)
48     {
49     	int right_border = array.length - 1;
50 
51     	do
52     	{
53     		int last_exchange = 0;
54 
55     		for (int i = 0; i < right_border; i++)
56     		{
57     			if (array[i].compareTo(array[i + 1]) > 0)
58     			{
59     				T temp = array[i];
60     				array[i] = array[i + 1];
61     				array[i + 1] = temp;
62 
63     				last_exchange = i;
64     			}
65     		}
66 
67     		right_border = last_exchange;
68     	}
69     	while ( right_border > 0 );
70     }
71 
72     public static void main(String[] args)
73     {
74         // create test array and fill it with random values
75         int[] array = new int[1024];
76         Random rnd = new Random();
77         for (int i = 0; i < array.length; i++)
78             array[i] = rnd.nextInt();
79 
80         // sort our array
81         bubble_sort(array);
82 
83         // check if it really sorted now
84         for (int i = 0; i < array.length - 1; i++ )
85         {
86              if (array[i] > array[i + 1])
87              {
88                  System.out.println("something wrong");
89                  return;
90              }
91         }
92 
93         System.out.println("array sorted");
94     }
95 }


hijacker
hijacker
hijacker
hijacker