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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • 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;
    }

  • Multidimensional array and chars

    Hi again,
    My apologies in advance if i can't word my question that well, i will try and be as clear and succinct as possible and hopefully for this newbie you can apprehend what i'm trying to figure out if i come up short.
    I'm trying to write a rather large control statement with a while loop and several nested ifs inside it that ultimately returns a single character after all is said and done, and then continually concatenates that character to a string which will eventually be output to a file. The part i'm stuck at is after i've changed the two letter characters into their ASCII values. I need to make the program take those two ASCII values and use them as a reference to a character in a multidimensional array of alphabetic characters, and then that character will be what is returned at the end.
    Here's the method, thanks in advance for your time.
    public String encode( String cipherKey )
            String textToEncode = input.next();
            String encodedText = " ";
            cipherKey = cipherKey.toUpperCase();
            textToEncode = textToEncode.toUpperCase();
            openFiles();
            int numberOfChars = textToEncode.length();
            int cipherPos = 0;
            int cipherLength = cipherKey.length();
            while (input.hasNext())
                for ( int count = 0; count < numberOfChars; count++ )
                    if (Character.isLetter(textToEncode.charAt(count)))
                        cipherPos %= cipherLength;
                        int xChar = (int) textToEncode.charAt(cipherPos);
                        int yChar = (int) textToEncode.charAt(count);
                        xChar -= 65;
                        yChar -= 65;
                        if ((xChar >= 0) && (xChar <= 25))
                            if ((yChar >= 0) && (yChar <= 25))
                        return ' ';
                     encodedText = encodedText +
        return encodedText; 
        }As you can see towards the end there are some incomplete statements where i became lost.

    its there, i couldnt c&p the whole program because it went over my character limit. Yeah it did compile but couldn't invoke my encode method without a NullPointerException.
    Here are the other methods in the class....
        public String setSource( String in )
            source = in;
            return source;
         Sets the value of the output file
         * @param out A <code>String</code> value representng name of output file.
         * @see #setSource
        public String setDestination( String out )
            destination = out;
            return destination;
         * Method to open both input and output files, and to test for exceptions
         * @see #encode
         * @see #decode
        private void openFiles()
        File inputFile = new File(source);  //Creates new file object from source file
        File outputFile = new File(destination);  //Creates new file object from destination file
            /* Tests whether input file exists and if so enables the Scanner
             * to read the data in from the source file. Catches SecurityException and
             * FileNotFoundException amd prints appropriate messages to user.
            if (inputFile.exists())
                try
                    input = new Scanner( new File( source ) );
                    FileReader reader = new FileReader(inputFile);
                    BufferedReader BufferIn = new BufferedReader(reader);
                catch ( SecurityException securityException )
                    System.err.println("You do not have read access to this file.");
                    System.exit( 1 );
                catch ( FileNotFoundException filesNotFoundException )
                    System.err.println("Error: File does not exist.");
                    System.exit( 1 );         
            /* Tests whether output file exists and if it does enables Formatter
             * to write encoded output to file. Catches SecurityException and
             * FileNotFoundException and prints appropriate message to user.
            if (outputFile.exists())
                try
                    output = new Formatter( new File( destination ) );
                catch ( SecurityException securityException )
                    System.err.println("You do not have write access to this file.");
                    System.exit( 1 );
                catch ( FileNotFoundException filesNotFoundException )
                    System.err.println("Error: File does not exist.");
                    System.exit( 1 );
         * Closes both input and output files after output file has been written
         * to.
         * @see #openFiles
        private void closeFiles()
            if ( output != null )
                input.close();
                output.close();
        }Edited by: fearofsoftware on Apr 17, 2009 8:35 PM

  • JNI multidimensional Array and OpenCV

    Hello everybody,
    my first post, so lets go..
    At the moment I am writing my thesis in the filed of automatic image classification. The project is written in Java, but I wanna use the OpenCV library from Intel (http://sourceforge.net/projects/opencvlibrary/) for facedetection.
    So far I managed to call the native method from Java. What I do I parse the path of the image to be analyzed as a string to my C++ programm. The faces are being detected and written into a so called CvSeq (http://www.comp.leeds.ac.uk/vision/opencv/opencvref_cxcore.htm#cxcore_ds_sequences) which holds the coordinates of the rectangles surrounding the found faces. Until now I can only call cvSeq->total which gives me the total number of faces as ints. That integer I return to my java api.
    What I don't know is, how to return a multidimensional array (2 dimensions) where the first dim contains the path as a string to the file and the second dimension 3 integers for x,y coordinates and the lenght of each rectangle.
    Or better, I might know how to return that Array, but not how to create it.
    I know this is somewht OpenCV specific, but maybe someone knows anything. Any little help would be greatly appreciated. Thanks a lot!!!!
    Regards
    Carsten
    attached: JNI source code
    /////////////////////////////////////////// source code ///////////////////////////////////////////////
    #include "cv.h"
    #include "highgui.h"
    #include "cxcore.h"
    #include "cxtypes.h"
    #include "cvaux.h"
    #include "org_kimm_media_image_data_JNIOpenCV.h"
    #include <stdio.h>
    JNIEXPORT jint JNICALL
    Java_org_kimm_media_image_data_JNIOpenCV_getFaces(JNIEnv *env, jobject object, jstring path)
    //declarations
    CvHaarClassifierCascade *pCascade = 0;
    CvMemStorage *pStorage = 0;
    CvSeq *pFaceRectSeq;
    int scale=1;
    jobjectArray recPoints;
    const char *str = env->GetStringUTFChars(path, 0);
    //initializations
    IplImage* pInpImg = cvLoadImage(str, CV_LOAD_IMAGE_COLOR);
    IplImage* small_image = pInpImg;
    pStorage = cvCreateMemStorage(0);
    pCascade = (CvHaarClassifierCascade *)cvLoad
         (("C:/OpenCV/data/haarcascades/haarcascade_frontalface_default.xml"),0, 0, 0 );
    //validaste that everything initilized properly
    if( !pInpImg || !pStorage || !pCascade)
         printf("Initialization failed: %s \n",
              (!pInpImg) ? "didn't load image file" :
              (!pCascade) ? "didn't load Haar Cascade --"
                   "make sure Path is correct" :
              "failed to allocate memory for data storage");
         exit(-1);
    //performance boost through reducing image size by factor 2          
              small_image = cvCreateImage( cvSize(pInpImg->width/2,pInpImg->height/2), IPL_DEPTH_8U, 3 );
    cvPyrDown( pInpImg, small_image, CV_GAUSSIAN_5x5 );
    scale = 2;
    //detect faces in image
    pFaceRectSeq = cvHaarDetectObjects(small_image, pCascade, pStorage,
                                            1.1,                                        //increase search scale by 10% each pass
                                            6,                                        //drop group of fewer than three detections
                                            CV_HAAR_DO_CANNY_PRUNING,          //skip regions unlikely to contain faces
                                                 cvSize(50,50));                         //use XML default for smallest search scale
    //initialize array for location of the faces (HERE IS WHERE I GET INTO TROUBLE!!!!!)
    int x = pFaceRectSeq->total;
    jclass intArrCls = env->FindClass ( "[I" ) ;
    recPoints = env->NewObjectArray ( x, intArrCls, NULL ) ;
    //for(int j = 0; j <= x; j++) {
    //   recPoints[j] = (jintArray)env->NewIntArray(3);
    for(int i=0;i<(pFaceRectSeq ? pFaceRectSeq->total:0); i++)
                                       CvRect* r = (CvRect*)cvGetSeqElem(pFaceRectSeq, i);
                                       CvPoint pt1 = {(r->x)*scale, (r->y)*scale};
                                       CvPoint pt2 = {(r->x + r->width)*scale, (r->y + r->height)*scale};
    //env->SetObjectArrayElement(recPoints,i, pt1.x);
    return pFaceRectSeq->total;
    }

    Any Java array you can consider like one-dimensional array of arrays n-1 dimension. For example, you have a 3 dim. array of objects:
    Object[][][] arr = new Object[1][2][6]; It can be considered as a set of one-dimensional arrays:
    ==========================================
    |  dim   |           Type
    ==========================================
      0          1 element, an array of type �[[Ljava/lang/Object;�
      1          1 x 2 elements , an arrays of type �[Ljava/lang/Object;�
    So you can convert three-dimensional array to one-dimensional array like in C++:
    |�[Ljava/lang/Object;� | �[Ljava/lang/Object;� | �[Ljava/lang/Object;�
         6 objects                 6 objects                 6 objects

  • Multidimensional Arrays + Me + OOP = Fear

    node.java
    class node {
         int[][] grid = new int[0][0];
         void detect(){
              System.out.println(grid);
    game.java
    class game {
         public static void main(String args[]) {
              node a = new node();
              a.detect();
    The output of this code is:
    http://img237.imageshack.us/img237/6556/outputxy7.png
    I am trying to create an imaginary grid so I can implement A* algorithm into my game which will later be an applet.
    Why did the output of this come out so weird? I do not understand multidimensional arrays and I struggle to understand object oriented programming.
    I have known Java since Nov 2006, but I have always dodge some of this difficult stuff. I am totally self taught and I have been learning through the Internet and a very old Java 2 book. So please speak "dumb" to me.
    Thank you,
    Andrew.

    Oh, grow up. If you get insulted this easily, you'll be inconsolable when you have to get a real job. I'm so sick of these children who want help but also want their genius to remain unquestioned.
    Anyway my point wasn't that you altered the image, but rather that you were careless in what you presented as data. Some of the stuff on that image couldn't possibly have worked with the code you posted. (In particular "java node" would not have even run. It wouldn't produce any output at all other than an error message.)
    Part of debugging is gathering real, useful, accurate information. And if you want help debugging you have to share real, useful, and accurate information. If you gather output and then change your code, you should at the very least make this clear.

  • Multidimensional arrays with enhanced for statement

    hello, do you know if it is possible to use enhanced for loop with multidimensional arrays, and if yes, then how?
    for example:
    int[][] arr = {{1,2},{3,4}};
    for(int i[][] : arr){
        doSomethingWith(i[][]);
    }

    The syntax is nice'n'easy:
    void f(int[][] m) {
        for(int[] row : m) {
            for(int x : row) {
    }

  • IndexOf on multidimensional array

    var clipArray:Array = new Array();
    clipArray[0] = new Array();
    clipArray[1] = new Array();
    clipArray[0][0]=2
    clipArray[0][1]=3
    clipArray[1][0]=4
    clipArray[1][1]=5
    trace(clipArray[0].indexOf(3));
    This traces '1' cause 3 can be found in [0][1] of the multidimensional array and 1 is the second value of that 0.
    Using indexOf this way I can determine that second value in which in this case the value 3 can be found.
    I want to to take this one step further and use indexOf somehow to determine the first value of the clipArray variable. So looking for 2 or 3 should trace 0 and looking for 4 or 5 should trace 1. Is there some way to do this?

    the following returns both indices:
    function indexOf2D(a:Array,v:*):Array{
    for(var i:int=0;i<a.length;i++){
    for(var j:int=0;j<a[i].length;j++){
    if(a[i][j]==v){
    return [i,j];
    return [-1,-1];

  • 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;

  • Multidimensional Array Sort

    Please help. I am very new to java and trying to build a multidimensional array. I have two variables 1)item_name and 2)item_value. These are values that I obtain by looping through a database result set. I need to build and array that can hold these variables. Once the multidimensional array is built I need to be able to sort it by item value.
    For example I would like to do something like this:
    while (rs.next)
    array.name = item_name
    array.value = item_value
    end
    array.sort(value)
    Thanks for any help!

    Don't use a multidimensional array. Use an array of objects, where the objects are of a class that you define. It might be something as simple as class Item that just has two fields--name and value--and their getters and setters. Or maybe just getters if you want the class to be immutable.
    Have the class implement Comparable and sort on value.
    If you sometimes want to sort on value and sometimes on name, then you'll need to either define two Comparators (one for name, one for value) or make the class Comparable on whichever is the more "natural" ordering and define a Comparator for the other one.
    Either put them in an array and use one of the java.util.Arrays.sort methods to sort them, or put them in a List (java.util.LinkedList or java.util.ArrayList) and use Collections.sort to sort them.

  • 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]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Sort Grid array and find the 4 corner dots.

    What I am trying to do is this:  I am using NI Visions find circles vi on a grid array or dots which gives me a 1D array of clusters.  In these clusters is the x,y coordinates of the grid dots that have been found.  I need to figure out which ones are the 4 corner dots and the 4 center dots along the edges.  The problem is the 1D array the find circle routine outputs is not in a logical order.  My grid could possibly change in size too.  Right now it is 14x12 but could be 13x12 or 14x13 or something like that. 
    I have found that if I send the 1D array of clusters though the sort 1D array it will sort it from top to bottom left to right, which I will then know that teh 1st element is the top left corner and the last element is the bottom right corner, but I am not sure what the easiest way is to figure out the rest of them. 
    Any help would be appreciated.
    I am using labview 7.1 and NI Vision 8.0
    Thanks
    Brad
    Brad Remenak
    Certified LabVIEW Architect

    Hi Brad,
    If you want to get the coordinates of specific dots on the image, you
    can search for the dots using different ROIs that only focus on certain
    areas of the image (ex: use an ROI that only searches in the
    upper-right corner so that you know the 1 match that shows up is
    definitely there).  Without knowing how consistent the dot
    locations are, I would suggest dividing up the ROI dimensions based on
    the variable size of the grid.
    Hope this helps,
    Irene Chow
    National Instruments

  • Question on System.arraycopy method and multidimensional array

    I'm trying to copy from single dimensional to multidimensional array using System.arraycopy method. The following is my problem.
    1) I need to specify the index of the multidimensional array while copying. Can I do that ? If yes , how???
    eg ; int a[] = new int[3];
    int b[] = new int[3][2]; I need to copy from a to b
    I tired the following and I'm getting an error.
    System.arraycopy(a,0,b[][1],0,3);
    How Can I achieve the above?? PLease Help --------------

    Java doesn't have multidimensional arrays. When you see an int[][] it's an array of arrays of ints. The arrays of ints might have different lengths like this one:int[][] arr =
    {{1,2,3,4},
    {1,2,3},
    {1,2},
    {1}
    };Do I need to say that arraycopy as you see it would fail in this case?
    If you know what kind of arrays you'll have you can simply implement your own arraycopy method (but it will not be as effecient as System.arraycopy) with a simple for-loop.

  • Copy array and sort the numbers in the new array

    Hi!
    I have an array containing some digits where some of the digits are zeros. I want to copy the digits to another array but the zeros (well, I actually want to copy the zeros as well but I want to have them in the end of the new array).
    I suppose I need an if-statement that checks if the old array contains any zeros and in that if-statement copy the content to the new array and put the zeros in the end.
    This is my code so far and I don�t know how to go on from here:
    int[] new_array = new int[array.length];
              for (int i = 0; i < array.length; i++)
                   if (array[i] > 0)
                        new_array[i] = array;
                        new_array = array;
                   System.out.print(new_array[i] + " ");

    Roxxor wrote:
    I think I know how to do it but only if I can catch the digits bigger than zero.
    My code below just checks if there are positive digits and if there are, the whole old array is copied to the new one.Yes. Don't do that, you can see it's wrong.
    So my problem is that I don�t know how to catch the digits bigger than zero and copy them. Is there any built in java keyword that catches signs, number etc?
    if (array>=0)
         new_array[i] = array[i];
         new_array = array;
    Yes, there is such a keyword. And you are already using it correctly in your code. You are already testing if the array entry is bigger than zero. Your only problem is, you don't know what to do when it is. But now you've been given two hints about what to do.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • 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.

  • 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.

Maybe you are looking for

  • Ability to print thru RIP (ImagePrint)

    Enhancement request; I use ImagePrint (RIP) to print, and the only possibility for me today is to print thru the sRGB color space - which obviously is a waste of color. The reason for this is Lightroom only allows printer color profiles for printing

  • Sticky computer name

    I've been having trouble changing the Computer Name on 4 identical (hardware-wise) PowerMac G5 machines. When we purchased them originally, I set their names to their serial numbers, but we're now implementing an organization-wide naming system. I ch

  • Error message on App World Upgrade

    Last night I upgraded App World on my Bold9700 and have been getting the following error message since:- Uncaught exception: java.lang.NoClassDefFoundError I cannot get into the App world at all since the upgrade. I have also tried rebooting the phon

  • Shuttle Items Display and processing

    Dear all, I am using apex 4 with 11g, I have a list of devices(processors, RAMs, DVDs), i want to assign these devices to some rack, where i need to add multiple devices at one time, for this shuttle seems me a better solution, if anyone please can s

  • ZTE OPEN C boot from SD card

    I have an ZTE OPEN C hardbricked into QHSUSB_BULK mode (trying to flash flame image) Does it support boot from SD card or there is any other method for debricking?