Problem Bubble sorting random array

For my CompSci class I have to create an array with random number in it and then do a bubble sort. I was able to create the array and input the variables in it but when it bubble sorts the array none of the values in the sorted array correlate to the original integers in the array.
Any help would be greatly appreciated.
public class RandomSort {
public static void main(String[] args) {
    final int ARRAY_SIZE = 20;
    final int RAND_MIN = 0;
    final int RAND_MAX = 100;
    int [] randomSort = new int [ARRAY_SIZE];
    int i;
    for (i = 0; i < randomSort.length; i++)
        randomSort[i] = (int) (Math.random()*(((RAND_MAX - RAND_MIN)+1)+RAND_MIN));
    for (i=0; i<ARRAY_SIZE; i++)
            for (int j = 0; j <=i-1; j++)
                    if (randomSort[j] > randomSort [j+1])
                        int temp = randomSort[j];
                        randomSort[j] = randomSort[j+1];
                        randomSort[j+1] = temp;
            System.out.println(randomSort);

Mmmhhh....
for (i = 0; i < ARRAY_SIZE; i++) {
     for (int j = ARRAY_SIZE - 1; j >= i + 1; j--) {
          if (randomSort[j - 1] > randomSort[j]) {
               final int temp = randomSort[j - 1];
               randomSort[j - 1] = randomSort[j];
               randomSort[j] = temp;
     System.out.println(randomSort);
Pffff....9
31
32
33
34
36
37
39
45
63
64
81
84
85
86
91
94
94
99
100Aarrfff...  [http://en.wikipedia.org/wiki/Bubble_sort|http://en.wikipedia.org/wiki/Bubble_sort]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Multidimensional Array and Bubble Sorting

    Goal:
    Bubble sort the array. I want to keep the data organized. So, 70 with aa, 20 with cc, 40 with ee and so foth.
    Example output....
    aa 70
    bb 30
    cc 40
    dd 90
    then..... by number
    ee 10
    cc 20
    bb 30
    ee 40
    Problem:
    I dont know how to bubble sort by letters. AND, a big and..., and I have not done a double array like this. (can you tell?) :)
    package bubleexample;
    public class BubbleSort
         public BubbleSort ()
         public void sortIntArray (int []  pIntArr)
              int     cnt;
              int     tmp = -1;
              for (int a = 0; a < pIntArr.length - 1; a++)
                   for (cnt = 0; cnt < pIntArr.length - 1; cnt++)
                        if (pIntArr [cnt] > pIntArr [cnt + 1])
                             tmp = pIntArr [cnt];
                             pIntArr [cnt] = pIntArr [cnt + 1];
                             pIntArr [cnt + 1] = tmp;
         public void displayArray (int [] pIntArray)
              for (int cnt = 0; cnt < pIntArray.length; cnt++)
                   System.out.println ("Array[" + cnt + "]: " + pIntArray [cnt]);
         public static void main (String []  args)
              int []  myNumberList = { 70, 20, 40, 10, 80, 60, 30 , 50, 30, 90 };
            String [] myLetterList = { "aa", "cc", "ee", "xx", "bb", "tt", "gg", "rr", "jj", "dd" };
              BubbleSort sortIntArray = new BubbleSort ();
              System.out.println ("Before Sorting");
              sortIntArray.displayArray (myNumberList);
            //sortStringtArray.displayArray (myLetterList);
              sortIntArray.sortIntArray (myNumberList);
            //sortStringArray.sortStringArray (myLetterList);
              System.out.println ("\nAfter Sorting");
              sortIntArray.displayArray (myNumberList);
            //sortStringArray.displayArray (myLetterList);
              System.exit (0);
    }If something is unclear, please let me know.

    incomplete example:
    class Movie
         private String name;
         private int rating;
         public Movie( String name, int rating )
              this.name = name;
              this.rating = rating;
         public String getName() { ..... }
         public int getRating() { ...... }
         public String toString() {} // recommended but you don't have to
    } // end of class Movie
    public class SortString2
         public static sort(..) {...}
         public static void main( String args[] )
              String[] names = {"Meet the Fockers","Blade",...};
              int[] ratings = {5,3,4,...}
              Movie[] movies = makeMovieArray( names, ratings );
              sort( movies );
              System.out.println(...);
              for ( Movie movie : movies )
                   System.out.printf( "movie:  %s\nrating:  %d\n\n", movie.getName(), movie.getRating() );
         public static Movie[] makeMovieArray( String[] names, int[] ratings )
              Movie[] movies;
              if ( names.length == ratings.length )
                   movies = new Movie[names.length];
                   for ( int i=0; i<names.length; i++ )
                        movies[i] = new Movie(names,ratings[i]);
                   return movies;
              else
                   return;
    } // end of class SortString2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Sorting randomly genareted string in alphapetic order

    import java.util.*;
    public class test {
        public static char[] chars;
        public static Random random;
        static {
            chars = new char[26];//taking caracters from asci table
            for (int i = 0; i < 26; i ++) {
                chars[i] = (char) (97 + i);           
            random = new Random ();
        public static void main (String[] args) { //printing random characters
                for (int i = 1; i <= 10; i++ ) {                                                                          
                System.out.println(randomString(20)); 
        private static String randomString (int length) { //generating random
            char[] array = new char[length];
            for (int i = 0; i < length; i ++) {
                array[i] = chars[random.nextInt (chars.length)];
        return new String (array);
        i have this code.i found that in the forums and modified it a bit.but i have still problems to sort randomly genareted strings in alphabetic order.i have a method to do it.but i couldn't implement it correctly.the way that i try to sort them is
    void sort(String[] a) {
      for (int i=0; i<a.length-1; i++) {
         for (int j=i+1; j<a.length; j++) {
            if (a.compareTo(a[j]) > 0) {
    String temp=a[j];
    a[j]=a[i];
    a[i]=temp;
    thats a method i try to use but i couldn't put it in a correct place in the code and couldn't call him.always it gives error.pls help this unexprienced java user...

    Hard to understand your problems, because you're too vague. At one point you mention you don't know where to put your method, at another you say you don't know how to call your method. If that is the case (which seems unlikely but oh well) here's an example.
    public class Testing9 {
         public Testing9() { // constructor
              String basicString = "BasicExample";
              String sortedString = mySortMethod(basicString); // call mySortMethod passing the string
              System.out.println("sortedString = " + sortedString);
         public static void main(String[] args) { // main method starts app
              Testing9 app = new Testing9(); // calls constructor
         public String mySortMethod(String s) { // put the method here cause I feel like it
              String sortedString = "";
              // do your own work here to sort, etc....
              return sortedString;
    }

  • File and bubble sort problem

    hey, I'm in a bit of a pickle.
    I'm trying to read from a file then bubble sort the file then write that to another file. Any suggestions how I can go about this. I've managed to read from the file, but have no idea how to bubble sort it.
    Any useful suggestions would be appreaciated

    Find the code below to read the numbers from nonsorted.txt frile in d: Drive and outputs the sorted into sorted.txt
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    public class BubbleSort {
         static StringBuffer newFile;
         static String FileNamewithpath = "d:/nonsorted.txt";
         static String NewFileNamewithpath = "d:/sorted.txt";
         static ArrayList numberList;
          * @param args
              public static void main(String args[]) {
                   newFile = new StringBuffer();
                   numberList = new ArrayList<Integer>();
                   try {
                        FileInputStream fstream = new FileInputStream(FileNamewithpath);
                        DataInputStream in = new DataInputStream(fstream);
                        StringBuffer sb = new StringBuffer();
                        // there are still some left to read
                        while (in.available() != 0) {
                             getNumbers(in.readLine());
                        in.close();
                        System.out.println(numberList);
                        numberList =  bubbleSortElements(numberList);
                        for (int i =0; i< numberList.size(); i++) {
                             newFile.append(Integer.parseInt(""+numberList.get(i)) + " ");
                        FileOut();
                   } catch (Exception e) {
                        e.printStackTrace();
                        System.err.println("File input error");
              public static void getNumbers(String str) {
                   StringTokenizer st = new StringTokenizer(str);
                   int i =0;
                   while (st.hasMoreTokens()) {
                        String word = st.nextToken();
                        numberList.add(word);
                        i++;
                   //return null;
              public static void FileOut() {
                   FileOutputStream out; // declare a file output object
                   PrintStream p; // declare a print stream object
                   try {
                        out = new FileOutputStream(NewFileNamewithpath);
                        p = new PrintStream(out);
                        p.println(newFile);
                        p.close();
                   } catch (Exception e) {
                        System.err.println("Error writing to file");
         public static  ArrayList bubbleSortElements(ArrayList numList ){
         try {
              int tmp;
              for (int i=0; i<numList.size()-1; i++) {
                     for (int j=0; j<numList.size()-1-i; j++)
                       if (Integer.parseInt(""+numList.get(j+1)) < Integer.parseInt(""+numList.get(j))) {  /* compare the two neighbors */
                         tmp = Integer.parseInt(""+numList.get(j));         /* swap a[j] and a[j+1]      */
                         numList.set(j,numList.get(j+1));
                         numList.set(j+1,tmp);
         } catch(Exception e) {
              e.printStackTrace();
              return numList;
    }

  • Two D bubble sort

    hello i'm trying to program a bubble sort with two D arrays..
    i have one-D array bubble sort but i couldn't figure out how the two D would work with the counter ..in my case..count1.
    public class BubbleSort {
    final int NUM = 20;
    int num[] = new int [NUM];
    int temp;
    public void input (){
    for (byte count = 0; count < NUMELEM; count ++)
         num[count] = (int)(Math.random()*2000)+1;
    public void BubbleSorting (){
         boolean swap = true;
         byte count1 = 0;
         while ((swap) && (count1 < NUM-1)){
         swap = false;
         for (byte count2 = 0; count2 < ((NUM-1)-count1); count2++){
              if (num[count2] > num[count2+1]){
                   temp = num[count2];
                   num[count2] = num[count2+1];
                   num[count2+1] = temp;
                   swap = true;
         count1 ++;
         System.out.println ("List After Pass Number " + count1 + " :");
         output();
    thanks in advance!

    please explain ur problem.
    i couldn't understand ur problem

  • Is this Bubble sort? How can I test it?

    Hi all,
    Would someone please confirm that this snippet of code uses the bubble sort algorithm to sort the array it receives? Also, would there be any difference in functionality, efficiency or otherwise if I rewrote the same method using recursion? I would also appreciate it if someone could suggest some test cases to test this code as I am not sure how I can go about doing that.
    Thank you very much.
    public static void sort (float array[]){
            int mIndex = 0;
            float temp;
            int i = 0, j = 0;
            for (i=array.length-1; i>0; i--){
                mIndex = i;
                for (j=0; j<i; j++){
                    if (array[j] > array[mIndex]){
                        mIndex = j;
                if (mIndex != i){
                    temp = array;
    array[i] = array[mIndex];
    array[mIndex] = temp;

    Moon123 wrote:
    Hi all,
    Would someone please confirm that this snippet of code uses the bubble sort algorithm to sort the array it receives? It doesn't. It uses [url http://en.wikipedia.org/wiki/Selection_sort]selection sort.
    Also, would there be any difference in functionality, efficiency or otherwise if I rewrote the same method using recursion? Functionality: By definition, no. That is, if you reimplement the same task using a different algorithm, by definition, it still performs the same function.
    Efficiency: No. The algorithm is still O(n^2). It will use more stack, and might be a tiny bit slower, but you won't be able to see the difference.
    I would also appreciate it if someone could suggest some test cases to test this code as I am not sure how I can go about doing that.Create an array. Stick values into it in varying orders, including: correctly sorted, reverse sorted, random. Pass the array to this method. Compare the result to what you know it should be.

  • How to sort StringBuffer array?

    I got a little problem regarding sorting a StringBuffer Array. As you all know arithmetic operation can't be perform on StringBuffer. So do I have any other alternative on sorting it? I try ".toString()" function but can't use also.

    Your talking about sorting the characters in a StringBuffer object, and not sorting an array of StringBuffers right? Well, isnt a StringBuffer basically a character array? If you use the getChars function, you can copy the StringBuffer into a character array, and from there use a bubble or quicksort to sort the characters...?

  • How to sort random number without the used of order by

    Hi ,
    how should 5 random number be sorted without the use of order by in PLSQL
    eg.
    id amount
    1 2
    2 9
    3 3
    4 5
    5 7
    Edited by: sake1 on 1-dec-2010 8:16

    I used Altavista and found one example, how does it look?
    DECLARE
      /* there is no built array in oracle, you must declare
      your own */
      TYPE Numarray IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
      /* the array of numbers - using assoc array because I can start
      with zero like traditional arrays */
      Nums Numarray;
      n NUMBER := 0;
      Temp NUMBER;
    BEGIN
      /* load up the array, put 20 random values in the array,
      in array indicies 0 to 19 */
      FOR i IN 0 .. 19
       LOOP
        Nums(i) :=  Round(Dbms_Random.Value(1, 1000));
      END LOOP;
      /* get the array size */
      n :=  Nums.Count();
      /* display the unsorted values - loop through the whole array and
      print out the values */
      Dbms_Output.Put_Line('unsorted:');
      FOR i IN Nums.First .. Nums.Last LOOP
        Dbms_Output.Put_Line(Nums(i));
      END LOOP;
      /* bubble sort - using two loops, compare each value with the one
      after it
      if the one after the current one is smaller , then
      switch their locations in the array, this is just like standard
      bubble sorts
      in other languages. The only real diff is the syntax.
      FOR i IN 0 .. n - 1 LOOP
        FOR j IN 0 .. n - (i + 1) - 1 LOOP
          IF (Nums(j) > Nums(j + 1)) THEN
            Temp := Nums(j);
            Nums(j) :=  Nums(j + 1);
            Nums(j + 1) :=  Temp;
          END IF;
        END LOOP;
      END LOOP;
      /* display the values sorted */
      Dbms_Output.Put_Line('sorted');
      FOR i IN Nums.First .. Nums.Last LOOP
        Dbms_Output.Put_Line(Chr(9) || Nums(i));
      END LOOP;
    END;
    unsorted:
    155
    909
    795
    977
    942
    214
    105
    269
    283
    820
    108
    594
    784
    921
    856
    736
    802
    457
    951
    411
    sorted
         105
         108
         155
         214
         269
         283
         411
         457
         594
         736
         784
         795
         802
         820
         856
         909
         921
         942
         951
         977
    */In the code the first comment is wrong actually i think, that one:
    "there is no built array in oracle, you must declare your own"
    I remember there were some system collection-types, if i'm not mixing with something, i remember there was some kind of such but they were un-documented ones, so we can juridically say that the comment in the code was still correct.

  • Help sort randomly generated integers

    I am having trouble with this peace of code; I wrote a little test and found the same problem in my larger program. My problem is I can't sort an array that I randomly put int values in but if I put them in manually the values will sort. And hits or help would be great.
    public class test {
        public static void main (String [] args) {
            int[] array = new int[20];
    // Generator random int into array
            for (int i=0; i<array.length; i++) {
                array[i] = (int)(Math.floor(Math.random() * (20.0 - 0.0)) + 0.0);
    // Selection sort
            int si, temp;
            si = 0;
            for(int i=0; i<=array.length-2; i++) {
                for(int j=i+1; j <=array.length-1; j++) {
                    if(array[j]<array)
    si = j;
    // Swap
    temp = array[i];
    array[i] = array[si];
    array[si] = temp;
    // Output
    for(int t=0; t<array.length; t++) {
    System.out.println(array[t]);

    This code will sort, and i am not asking anyone to do it for me, just and hits on what the problem could be.
    public class test {
        public static void main (String [] args) {
            int[] array    = {9,8,4};
    // Generator random int into array
            for (int i=0; i<array.length; i++) {
                array[i] = (int)(Math.floor(Math.random() * (20.0 - 0.0)) + 0.0);
    // Selection sort
            int si, temp; 
            si = 0;
            for (int i=0; i<=array.length-2; i++) {
                for (int j=i+1; j<=array.length-1; j++) {
                    if(array[j] < array) {
    si = j;
    // Swap
    temp = array[i];
    array[i] = array[si];
    array[si] = temp;
    // Output
    for(int t=0; t<array.length; t++) {
    System.out.println(array[t]);

  • Problem with sorting

    Hi all,
    I am trying to sort an array using Bubble sort, But it can't seem to work.
    can you please look at my code below and tell me where I am going wrong
    bubbleSort class
    public class bubbleSort {
        int size;
        int[] array;
        public bubbleSort(int size, int[] array) {
            this.size = size;
            this.array = array;
        public void sort(int[] arr, int arraySize) {
            boolean swapped;
            arr = this.array;
            arraySize = this.size;
            int temp;
            do {
                swapped = false;
                for (int i = 0; i < arraySize - 1; i++) {
                    if (arr[i] > arr[i + 1]) {
                        temp = arr;
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    swapped = true;
    } while (swapped != true);
    public void swappFunction(int num1, int num2) {
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
    public void printArray(int[] arr, int arraySize) {
    for (int i = 0; i < arraySize; i++) {
    System.out.println(arr[i] + " ");
    Main class
    {code:java}
    public class Main {
        public static void main(String[] args) {
            int unsortedArray[] = {12,9,4,99,120,1,3,10};
            bubbleSort bbl_sort = new bubbleSort( unsortedArray.length,unsortedArray);
            System.out.println("Unsorted Array");
            bbl_sort.printArray(unsortedArray, unsortedArray.length);
            bbl_sort.sort(unsortedArray, unsortedArray.length);
            System.out.println("Sorted Array");
            bbl_sort.printArray(unsortedArray, unsortedArray.length);

    Try it this way. I commented out the parts that you were trying to make a copy of an array therefore passing by value instead of by reference. You need the side effects reflected on the array otherwise you may need to return an array if you decide to pass by value. I also added a j variable because at the end of each iteration, the last value in the array is sorted, so no need to redo it each time. In addition, you can get the length of the array by using array.length instead of passing the size of the array.
    public class bubbleSort {
        int size;
        int[] array;
        public bubbleSort(int size, int[] array) {
            this.size = size;
            this.array = array;
        public void sort(int[] arr, int arraySize) {
            boolean swapped;
            int j = 0;
           // arr = this.array;
            //arraySize = this.size;
            int temp;
            do {
                swapped = false;
                j++;
                for (int i = 0; i < arraySize - j; i++) {
                    if (arr[i] > arr[i + 1]) {
                        temp = arr;
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    swapped = true;
    } while (swapped);
    public void swappFunction(int num1, int num2) {
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
    public void printArray(int[] arr, int arraySize) {
    for (int i = 0; i < arraySize; i++) {
    System.out.println(arr[i] + " ");
    public static void main(String[] args) {
    int unsortedArray[] = {12,9,4,99,120,1,3,10};
    bubbleSort bbl_sort = new bubbleSort( unsortedArray.length,unsortedArray);
    System.out.println("Unsorted Array");
    bbl_sort.printArray(unsortedArray, unsortedArray.length);
    bbl_sort.sort(unsortedArray, unsortedArray.length);
    System.out.println("Sorted Array");
    bbl_sort.printArray(unsortedArray, unsortedArray.length);

  • My bubble sort doesn't work, and does anyone know

    how to count and print the scores of a certain grade.... all the 90's with a's, all the 80's with b's etc.... This is my first java program with two classes. I've been messing with it for about 24hours over the last week. :O. Any suggestions?
    import java.util.Scanner;
    public class GradeSort {
         public static void main(String [] args){
              //Scanner keyboard = new Scanner(System.in);
              System.out.println("How many students took the test?");
              Scanner kbd = new Scanner(System.in);
              int NUM_STUDENTS = kbd.nextInt();
              double [] grades = new double[NUM_STUDENTS];//Assn array
              readReadingsInto(grades);
              System.out.printf( "\nThe average is %.3f%n", average(grades));
              print(grades);}
              private static void readReadingsInto(double [] array){
                   Scanner keyboard = new Scanner(System.in);
                   for (int i =0; i < array.length; i++) {
                   System.out.print("enter grade # " + (i+1)+ "/" );
              array[i] = keyboard.nextInt();
         public static double average(double [] anArray){
              double sum = 0.0;
              for (double item : anArray){
                   sum += item;
              return sum/anArray.length;
    public static void bubbleSort ( double [] anArray )
    for (double i = anArray.length-1; i > 0; i-- )
    for ( int j = 0; j < i; j++ )
    if ( anArray[j] > anArray[j+1] )
    double temp = anArray[j];
    anArray[j] = anArray[j+1];
    anArray[j+1] = temp;}
    public static void print(double [] arr) {
         for (int i = 0; i < arr.length; i++){
              Grade gRade = new Grade(arr);
              System.out.println("Reading #" + (i+1)+" " + arr[i] + " " + gRade.letter() );
              //Grade gRade = new Grade(reading);
              //System.out.println( gRade.letter() );
              //System.out.print ( grades[1] );
    public class Grade {
         public static final double MIN = 0.0;
         public static final double MAX = 100.0;
         public Grade(double gRade){
              if (gRade < MIN || gRade > MAX){
                   System.err.println("Grade(): bad argument recievived: " + gRade);
              } else {
                   myValue = gRade;
    public String letter(){
         if (myValue < MIN || myValue > MAX){ return "error";}
    else if (myValue >= 90){return "A";}
    else if (myValue >= 80){return "B";}
    else if (myValue >= 70){return "C";}
    else return "Fail";     }
    private double myValue;

    Let me see if I can fix the formatting for you. The bubble sort, isn't sorting? The print after the sort is in the same order as I input the data.
    import java.util.Scanner;
    public class GradeSort {
         public static void main(String [] args){
              //Scanner keyboard = new Scanner(System.in);
              System.out.println("How many students took the test?");
              Scanner kbd = new Scanner(System.in);
              int NUM_STUDENTS = kbd.nextInt();
              double [] grades = new double[NUM_STUDENTS];//Assn array
              readReadingsInto(grades);
              System.out.printf( "\nThe average is %.3f%n", average(grades));
              print(grades);}
              private static void readReadingsInto(double [] array){
                   Scanner keyboard = new Scanner(System.in);
                   for (int i =0; i < array.length; i++) {
                   System.out.print("enter grade # " + (i+1)+ "/" );
              array[i] = keyboard.nextInt();
         public static double average(double [] anArray){
              double sum = 0.0;
              for (double item : anArray){
                   sum += item;
              return sum/anArray.length;
    public static void bubbleSort ( double [] anArray )
            for (double i = anArray.length-1; i > 0; i-- )
              for ( int j = 0; j < i; j++ )
                  if ( anArray[j] > anArray[j+1] )
                        double temp = anArray[j];
                        anArray[j] = anArray[j+1];
                        anArray[j+1] = temp;}
    public static void print(double [] arr) {
         for (int i = 0; i < arr.length; i++){
              Grade gRade = new Grade(arr);
              System.out.println("Reading #" + (i+1)+" " + arr[i] + " " + gRade.letter() );
              //Grade gRade = new Grade(reading);
              //System.out.println( gRade.letter() );
              //System.out.print ( grades[1] );
    The other class is:
    public class Grade {
         public static final double MIN = 0.0;
         public static final double MAX = 100.0;
         public Grade(double gRade){
              if (gRade < MIN || gRade > MAX){
                   System.err.println("Grade(): bad argument recievived: " + gRade);
              } else {
                   myValue = gRade;
    public String letter(){
         if (myValue < MIN || myValue > MAX){ return "error";}
    else if (myValue >= 90){return "A";}
    else if (myValue >= 80){return "B";}
    else if (myValue >= 70){return "C";}
    else return "Fail";     }
    private double myValue;

  • How do i add a new data type in this Bubble sort

    i have tried to i add a new String data type (String publisher) but my program has an error.
    please show me
    // libmainsys.java
    // demonstrates bubble sort
    // to run this program: C>java BubbleSortApp
    class ArrayBub
    private String[] a; // ref to array a
    private int nElems; // number of data items
    public ArrayBub(int max) // constructor
    a = new String[max]; // create the array
    nElems = 0; // no items yet
    public void insert(String value) // put element into array
    a[nElems] = value; // insert it
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    System.out.print(a[j] + " "); // display it
    System.out.println("");
    public void bubbleSort()
    int out, in;
    for(out=nElems-1; out>1; out--) // outer loop (backward)
    for(in=0; in<out; in++) // inner loop (forward)
    if( a[in].compareTo(a[in+1])>0 ) // out of order?
    swap(in, in+1); // swap them
    } // end bubbleSort()
    private void swap(int one, int two)
    String temp = new String(a[one]);
    a[one] = a[two];
    a[two] = temp;
    } // end class ArrayBub
    class libmainsys
    public static void main(String[] args)
    int maxSize = 100; // array size
    ArrayBub arr; // reference to array
    arr = new ArrayBub(maxSize); // create the array
    arr.insert("Manuel"); // insert 10 items
    arr.insert("Portillo");
    arr.insert("Kike");
    arr.insert("Pedro");
    arr.insert("Mono");
    arr.insert("Cuca");
    arr.insert("Zoila");
    arr.insert("Karina");
    arr.insert("Joto");
    arr.display(); // display items
    arr.bubbleSort(); // bubble sort them
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys
    /////////////////////////////////////////////

    nope i mean like this
    // libmainsys.java
    // demonstrates bubble sort
    // to run this program: C>java BubbleSortApp
    class ArrayBub
    private String[] a; // ref to array a
    private Sting[] publisher;
    private int nElems; // number of data items
    public ArrayBub(int max) // constructor
    a = new String[max]; // create the array
    nElems = 0; // no items yet
    public void insert(String value) // put element into array
    a[nElems] = value; // insert it
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    System.out.print(a[j] + " "); // display it
    System.out.println("");
    public void bubbleSort()
    int out, in;
    for(out=nElems-1; out>1; out--) // outer loop (backward)
    for(in=0; in<out; in++) // inner loop (forward)
    if( a[in].compareTo(a[in+1])>0 ) // out of order?
    swap(in, in+1); // swap them
    } // end bubbleSort()
    private void swap(int one, int two)
    String temp = new String(a[one]);
    a[one] = a[two];
    a[two] = temp;
    } // end class ArrayBub
    class libmainsys
    public static void main(String[] args)
    int maxSize = 100; // array size
    ArrayBub arr; // reference to array
    arr = new ArrayBub(maxSize); // create the array
    arr.insert("Manuel"); // insert 10 items
    arr.insert("Portillo");
    arr.insert("Kike");
    arr.insert("Pedro");
    arr.insert("Mono");
    arr.insert("Cuca");
    arr.insert("Zoila");
    arr.insert("Karina");
    arr.insert("Joto");
    arr.display(); // display items
    arr.bubbleSort(); // bubble sort them
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys
    but i have no idea what to do next

  • How do I open a text file to sort using bubble sort?

    Hi,
    I have a text file, which is a list of #'s.. ex)
    0.001121
    0.313313
    0.001334
    how do you open a text file and read a list? I have the bubble sort code which sorts.. thanks

    I wrote this, but am getting a couple errors:
    import java.util.*;
    import java.io.*;
    public class sort
         public static void main(String[] args)
              String fileName = "numsRandom1024.txt";
              Scanner fromFile = null;
              int index = 0;
              double[] a = new double[1024];Don't use double. You should use something that implements Comparable, like java.lang.Double.
              try
                   fromFile = new Scanner(new File(fileName));
              catch (FileNotFoundException e)
    System.out.println("Error opening the file " +
    " + fileName);
                   System.exit(0);
              while (fromFile.hasNextLine())
                   String line = fromFile.nextLine();
                   a[index] = Double.parseDouble(line);Don't parse to a double, create a java.lang.Double instead.
                   System.out.println(a[index]);
                   index++;
              fromFile.close();
              bubbleSort( a, 0, a.length-1 );No. Don't use a.length-1: from index to a.length-1 all values will be null (if you use Double's). Call it like this:bubbleSort(a, 0, index);
    public static <T extends Comparable<? super T>> void
    d bubbleSort( T[] a, int first, int last )
              for(int counter = 0 ; counter < 1024 ; counter++)
    for(int counter2 = 1 ; counter2 < (1024-counter) ;
    ) ; counter2++)Don't let those counter loop to 1024. The max should be last .
                        if(a[counter2-1] > a[counter2])No. Use the compareTo(...) method:if(a[counter2-1].compareTo(a[counter2]) > 0) {
                             double temp = a[counter2];No, your array contains Comparable's of type T, use that type then:T temp = a[counter2];
    // ...Good luck.

  • Sorting an array of objects and returning another variable

    Hi there,
    Bit stuck on this one I wonder if anyone can help..
    I have an object array into which I've pushed a number of objects with different variables :-
    myArray.push({myRef: 1, myValue: "W"});
    I can sort the array in numerical order using :-
    myArray.sortOn("myRef", Array.NUMERIC);
    but after sorting I would like to collapse the array using something along the lines of :-
    myArray.join("");
    to join the OTHER variable (myValue)...
    Is it possible to do this without pushing every instance of 'myValue' to another array and then joining that ?
    Many Thanks in advance
    Martin

    Hi kglad,
    I really appreciate you helping, but I have had to completely change my approach to this problem, therefore I will be marking the question as answered !!
    Thanks again

  • Urgent Help with Bubble Sort

    alright the goal here is to sort the array by year of birth which is stored in a class elsewhere. but the problem lies in the IF statement:
    if (peopleArray[i] > peopleArray[i + 1])
    it says that the operator > cannot be applied, what does this mean and how can I fix it:
    WHOLE CODING:
    * A Database is a collection of persons (staff, student and faculty).
    * A very simple database of people in a university. This class simply stores
    * persons in an ArrayList and, at request, lists them on standard output.
    * A first look at arrays.
    * @author: Keitha Murray, James Devlin
    * @version: January 2002, February 2002
    public class Database
    Person[] peopleArray = new Person[50];
    int lastpos;
    int nextpos;
    int temp;
    int lastPosition;
    int nextFree;
    * Create a new, empty person database.
    public Database()
    lastpos = 0;
    nextpos = 0;
    lastPosition = nextFree - 1;
    * Add a person to the database.
    * @param aPerson the person to add
    public void addPerson(Person aPerson)
    peopleArray[nextpos] = aPerson;
    lastpos = nextpos;
    nextpos++;
    * List all the persons currently in the database on standard out.
    public void listAll ()
    for (int i = 0; i < nextpos; i++)
    System.out.println(peopleArray.toString());
    public void sortArray()
    for (int j = 0; j < lastPosition; j++)
    for (int i = 0; i < lastPosition; i++)
    if (peopleArray[i] > peopleArray[i + 1])
    temp = peopleArray[i];
    peopleArray[i] = peopleArray[i + 1];
    peopleArray[i + 1] = temp;

    I'm guessing there's a whole bunch of "[ i ]" characters not shown here because of the code tag so I'll ignore that issue.
    You can't compare an entire Person object using ">". You need to specify the field or method.
    e.g. if (peopleArray[ i ].getYear() > peopleArray[i + 1].getYear() ) {

Maybe you are looking for

  • Restore iPhotoLibrary specifically from EXTERNAL Hard drive  Time Machine back up?

    My laptop Photo Library is corrupted somehow. I tried to restore from a prior in Time Machine on laptop and made the mistake of not saying to keep BOTH copies,  but after trying for 3 hours of telling me it was doing it through various windows, a lit

  • PS CS 6 & LR 4.1 problems with Raw

    There seems to be a big problem with CS6 (and LR4.1.) with some raw files. My computer has now been logged in twice by adobe support personel trying to fix the problem with no luck. First photoshop was not able to open Canon 5D mk3 / CR2 raw files- t

  • Adobe Premiere Elements 13 stops working trying to add media via videos from camera

    When I try to add media selecting videos from camera or flip, Adobe Premiere Elements 13 stops working and closes. What might be the problem?

  • How table statistics going to affect insert statements

    I have 2 DB's.I have a process in both DB's which will load records in to tab1 using sql loader.Tab1 in DB1 is not analyzed since 2005 while tab1 in DB2 is recently analyzed.My SQL ldr process is slow in DB1 when compared to DB2. I am wondering how s

  • Abssence Management/Reporting

    Hi Gurus, Could you please advise me. 1) Is it possible to make a absence report more specific? The reason for this is we need information such as percentages of people off sick. I know this can be done manually after producing a report, but is very