hi all

i need a bubble sort algorithm in Java and make a class bubble_sort
to sort any given array of any user defined type.

can any of u give me a basic algoruthm i need to work with????

2 for loops with int I and K

if (num[i] > num[k])
swap = num[k]
num[k] = num[i]
num[i] = swap

to change the order(ascending/decending) just change the > to < or vica versa

Edited 6 Years Ago by phoenix911: n/a

try a search engine. There's tons of resources explaining exactly what bubble sort is as well as what a class is.
Combine the two and you're good to go.

hi

i do know how to carry out a normal bubble sort. what i am interested in is it shud work with any user defined function.therefore i im guessing i need to work with casting. im familiar with the switching part . for eg im passing a structure or a class into the sort function.the compiler should determine which it has to sort

2 for loops with int I and K

if (num[i] > num[k])
swap = num[k]
num[k] = num[i]
num[i] = swap

to change the order(ascending/decending) just change the > to < or vica versa

create a class which is of type <T> and then it accepts any type given to it... which will throw exceptions if you dont cater for the types

Maybe this will help.

public static void Sort(int d[]){

        int next;
        int temp;
        int index;

            for(index = 0; index < d.length - 1; index++){
                for(next =  0; next < d.length - 1; next++){
                    if( d[next] > d[next+1] ){
                        temp = d[next];
                        d[next] = d[next+1];
                        d[next+1] = temp;
                    }
                }
           }
        }// Sort

For a sorting algorithm ( or any class for that matter ) that can work for ANY type, user defined or not, you are going to have to know a bit about Generics in java. Also, for a sorting algorithm those types must be comparable.

If you do not know much about Generics, or comparable objects, you should take a look at the Java API ( especially the Comparator and Comparable interfaces ).

This BubbleSort class will assume every type extends Comparable ( there are other ways to do this, just familiarise yourself with generics ) :

public class BubbleSort<T extends Comparable<T>> {
  // Constructor and methods...
}

If you lookup Generics and the interfaces mentioned above, you should be able to create a Bubble Sort class that takes any type quite easily!

This article has been dead for over six months. Start a new discussion instead.