Selection Sort and arrays

Hey im trying to pass a selection sort into an array. Here is my code....
public class SortTest {
     public static void main(String args[]) {
          int[] array = new int[20];
          SelectionSort ss = new SelectionSort();
          InsertionSort is = new InsertionSort();
          BubbleSort bs = new BubbleSort();
          System.out.println("Normal Array: ");
          System.out.println();
          for (int i = 0; i < 20; i++) {
               array[i] = (int) (Math.random() * 60 + 40);
               System.out.println(array);
               ss.sort(array);
               System.out.println(array[i]);
the ss.sort(array) is a method that has the selection sort code in it. I knwo the codes right too..My code prints out 10 sorted items and 10 items are 0. Anyone know why this is happening?

ok here is what my output is:
0
0
0
0
0
0
0
0
0
0
45
52
66
66
69
69
69
79
79
79
here is the selectino sort code:
public class SelectionSort {
     public void sort (int numbers[])
          int min, temp;
          for (int index = 0; index < numbers.length - 1; index++)
               min = index;
               for (int scan = index + 1; scan < numbers.length; scan++){
                    if (numbers[scan] < numbers[min])
                              min = scan;
               temp = numbers[min];
               numbers[min] = numbers[index];
               numbers[index] = temp;
}here is my test class updated a little:
public class SortTest {
     public static void main(String args[]) {
          int[] array = new int[20];
          SelectionSort ss = new SelectionSort();
          InsertionSort is = new InsertionSort();
          BubbleSort bs = new BubbleSort();
          for (int i = 0; i < 20; i++) {
               array[i] = (int) (Math.random() * 60 + 40);
               ss.sort(array);
               System.out.println(array);
sorry i didn't provide it earlier..

Similar Messages

  • 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

  • Sorting and filtering by select-multi person or group field in the list in SharePoint 2013

    Hi everybody,
    In SharePoint 2013, I have defined a column as "Person or Group" field, which you allow for multiple selections. when I try to sort/filter it by this field in the list. The field doesn't show up in the dropdown. If I changed "Allow multiple
    selections" option to "No" by clicking the column name to edit it in "List Settings", the field can show up sort in the dropdown.
    How about support sorting and filter by select-multiple "Person or Group" field in sharepoint 2013?
    BTW, in SharePoint 2010, it can support this issue no matter what the "Allow multiple selections" option the request is.
    Any help would be great!
    Thanks,
    Jodie

    Hi Jodie,
    Can you please give this as a try.
    To fix the Filter Issue on Assigned To Column. We need to run the following scripts.
    The field which allows more than one values or which allows multiple selections. The multi-valued fileds are non-sortable,
    non-filterable. Multi-valued fields cannot be indexed
    $web=Get-SPWeb
    $list=$web.Lists[] $field=$list.Fields[ColumnName] $strSchema=$field.SchemaXml $str=Schema$strSchema.Replace("Sortable=`"FALSE`"","Sortable=`"true`"")
    $field.SchemaXml = $strSchema
    Krishana Kumar http://www.mosstechnet-kk.com
    Thanks for your reply, I have tried to run the scripts, but it still cannot work. The following is my scripts:
    $web=Get-SPWeb 'http://cst-server-01'
    $list=$.web.Lists["Product Request"]
    $field=$list.Fields["Applicant"]
    $strSchema=$field.SchemaXml
    $str=Schema$strSchema.Replace("Sortable='"FALSE'"", "Sortable='"True'"")
    $field.SchemaXml = $strSchema

  • 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

  • Sorting and Searching String (Please help me)

    Hi, Could somn please be of any help here. I am trying to sort this string in alphabetical order and then search for data available but I am not makingprogress with the code. Does anyone have any advise or better still the code to solve this problem... This is hat I have at the moment
    import java.util.*;
    import java.io.PrintStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    public class coursework2
         public static final int MAX_RECORDS = 20;
         public static String lastName[] = new String[MAX_RECORDS];
         public static String firstName[] = new String[MAX_RECORDS];
         public static String telNumber[] = new String[MAX_RECORDS];
         public static String emailAddress[] = new String[MAX_RECORDS];
         public static int read_in_file(String file_name)
              Scanner read_in;
              Scanner line;
              int record_count = 0;
              String record;
              try
                   read_in = new Scanner(new File(file_name));
                   // read in one line at a time
                   read_in.useDelimiter(System.getProperty("line.separator"));
                   while (read_in.hasNext())
                        // Test to see if there are too many records in the file
                        if (record_count == MAX_RECORDS)
                             System.out.printf("Only %d records allowed in file", MAX_RECORDS);
                             System.exit(0);
                        // read in record
                        record = new String(read_in.next());
                        // Split the record up into its fields and store in
                        // appropriate arrays
                        line = new Scanner(record);
                        line.useDelimiter("\\s*,,\\s*");
                        lastName[record_count] = line.next();
                        firstName[record_count] = line.next();
                        telNumber[record_count] = line.next();
                        emailAddress[record_count] = line.next();
                        // Increment record count
                        record_count++;
              catch (FileNotFoundException e)
                   e.printStackTrace();
              return record_count;
         public static void write_out_file(int no_of_records, String filename)
              PrintStream write_out;
              int counter;
              try
                   // Create new file
                   write_out = new PrintStream(new File(filename));
                   // Output all reacords
                   for(counter = 0; counter < no_of_records; counter++)
                        // Output a record
                        write_out.print(lastName[counter]);
                        write_out.print(",,");
                        write_out.print(firstName[counter]);
                        write_out.print(",,");
                        write_out.print(telNumber[counter]);
                        write_out.print(",,");
                        write_out.println(emailAddress[counter]);
                   // Close file
                   write_out.close();
              catch (FileNotFoundException e)
                   e.printStackTrace();
         // Your 'functions' go here
         //This code sorts out the record after loaded into alphabetical order using
         //the selection sort method
         public static void sort()
         // Your 'main' code goes here
         //The code below uses a binary search method to search for record because
         //record have been sorted and this would make search faster and more efficient
         public static boolean linearSearch(String strFirstName, String strLastName)
              //Set-up data_input and declare variables
              //This linear search searches for record in the contact application.
              //Search for a record using surname only
                   int i = 0;
                   boolean found = false;
                   while (!found && i < lastName.length)
                        if(strFirstName.equals("") && strLastName.equals(""))
                             return true;
                        if(lastName.equalsIgnoreCase(strLastName)){
                   //List records from surname only
                   System.out.println("Enter your search criteria (last name only):");
                        System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                        System.out.println("");
                        if (lastName[i].compareTo(strLastName) == 0)
                             //Compare the last name values and type to make sure they are same.
                             found = true;
                                  i++;
                                  System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                                       System.out.println("");
                             return found;
              //Search for a record using first name only
         public static void main(String[] args)
              // Set-up data input
              Scanner data_input = new Scanner(System.in);
              // Declare Variables
              int number_of_records;
              String filename;
              int counter;
              // Get filename and read in file
              System.out.print("Enter the masterfile file name: ");
              filename = data_input.next();
              number_of_records = read_in_file("data2.dat");
              //Get new filename and write out the file
              System.out.print("Enter new masterfile file name: ");
              filename = data_input.next();
              //System.out.println("Enter your search criteria (first or last name):");
              linearSearch("*", "");
    Am very sorry this is long, the file should be sorted after it is loaded and I have that, You can make up some data with last ane, first name, tel and email to show me an example. Thanks alot
    Joseph

    Hi Monica, Thanks for you patience with me.
    I have tried writing a selection sort method but am having some errors. Could you kindly have a lookand correct me please.
    This is the code i wrote
    public static void selectionSort(Comparable [] data)
              String strFirstName;
              String strLastName;
              Comparable temp;
              for(int i = 0; i < lastName.length; i++)
                   lastName = index;
                   for (int j = i; j < lastName.length; j++)
                        if (lastName[j].compareTo(lastName) < 0)
                             lastName[j] = lastName[i];
                   //Swap the string values
                   temp = lastName[j];
                   lastName[j] = lastName[i];
                   lastName[i] = temp;
    As you requested, below are 4 error messages I had
    E:\coursework2.java:101: cannot find symbol
    symbol : variable index
    location: class coursework2
                   lastName = index;
    ^
    E:\coursework2.java:107: cannot find symbol
    symbol : variable j
    location: class coursework2
                   temp = lastName[j];
    ^
    E:\coursework2.java:108: cannot find symbol
    symbol : variable j
    location: class coursework2
                   lastName[j] = lastName[i];
    ^
    E:\coursework2.java:109: incompatible types
    found : java.lang.Comparable
    required: java.lang.String
                   lastName[i] = temp;
    ^
    4 errors
    JCompiler done.
    JCompiler ready.
    Joseph

  • Selection Sort troubles

    I am doing a practice exercise involving a Selection Sort. I keep getting 2 errors when I compile and not sure what to do to fix them. Thanks in advance for your help! Here are the two errors:
    SortArray.java:79: illegal start of expression
         private void swapEm ( int indexCheck, int min ){
            ^
    SortArray.java:67: cannot resolve symbol
    symbol  : method swapEm  (int,int)
    location: class SortArray
               swapEm( indexCheck, min );
                     ^Here is my code:
    import java.lang.Math.*;
    public class SortArray {
         * Main method for program.
         * @param  args
        public static void main ( String args[] ){
         int array[] = new int [25]; //variable for array
          * For loop to populate the array with numbers ranging
          * from 0-100 inclusively and then
          * printing them out on the screen.
         for ( int index = 0; index < array.length; index ++ ){
             array[index] =( ( int ) ( Math.random() * 101 )  );
             System.out.println( array[index] );
          * For loop that iterates through array and sorts the array
          * in ascending order.
         int min;
         for ( int indexCheck = 0; indexCheck <  array.length -1;
               indexCheck ++ ){
             min = indexCheck;
             for ( int index = indexCheck + 1; index < array.length;
               index ++ ){
              if ( array[index] < min ){
                   min = array[index];
               swapEm( indexCheck, min );
          * Swaps the values of the array to put them in order.
          * @param one a value of type 'int'
          * @param two a value of type 'int'
         private void swapEm ( int indexCheck, int min ){
             int temp = array[indexCheck];
             array[indexCheck] = array[min];
             array[min] = temp;
         System.out.println();
         for ( int intCounter = 0; intCounter < array.length;
               intCounter ++ ){
             System.out.println( array[intCounter] );
    }//SortArray.java

    This is how i would do it:
    for ( int index = 0; index < array.length; index ++ ){
                   array[index] =( ( int ) ( Math.random() * 101 )  );
                   System.out.println( array[index] );
              System.out.println("-----------");
              /* To sort the array in ascending order
              for (int i=0; i<25; i++) {
                   for (int j=i+1; j<25; j++) {
                        if (array[i] > array [j]) {
                             int temp = array;
                             array[i] = array [j];
                             array[j] = temp;
              for (int i=0; i<25; i++)
                   System.out.println ("" + array[i]);
    All inside your main() method, without even using other methods.
    Calin

  • Swap Counter in simple Selection Sort method

        void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                   int temp = list[maxIndex];        //
                   list[maxIndex] = list[i-1];         //         Is the problem here?        
                   list[i-1] = temp;                     //
                   swapCount++;                     //
              System.out.println("\n" +swapCount+ " swaps were needed. ");
        }This is a pretty simple selection sort method. But I am fairly sure that I am incorrectly counting swaps with the code. I have defined a "swap" as when two array indices have their values switched. I am convinced that there is something wrong because the array of numbers is randomly generated, and yet the swapCount counter is always equal
    to (list.length-1) when it prints out. I would think it should be different every time. I indicated the line where I believe the problem lies, but I am not for sure. Thanks everybody.

    List of Random Integers, then sorted:
    9, 29, 30, 42, 53, 58, 59, 64, 66, 69, 74, 79, 79, 87, 95
    9 swaps were needed.then sort again (descending) and get this:
    95, 87, 79, 79, 74, 69, 66, 64, 59, 58, 53, 42, 30, 29, 9
    1 swaps were needed.I'm pretty sure that isn't correct. But forgive me if I did not specify that it was to work in descending order as well.
    So I tried this:
    void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                  if (maxIndex != (i-1) && ascending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
                  else if (maxIndex != (i+1) && descending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
    } adding the i+1 (because it is going in a different order)...and I think I solved it!

  • Comparable interface selection sort

    Hi,
    I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday).
    Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is.
    I have created a selction sort but dont know how to call the birthday from my array list and then to sort it.
    This is my code for the selection sort so far:
    import java.util.ArrayList.*;
    public class Main
    public static void selectionSort(Comparable[] people)
    for (int k = people.length-1; k>0; k --)
    Comparable tmp;
    int Large = 0;
    for (int j=1; j<= k; j++)
    if (people[j].compareTo(people[k]) <0)
    Large = j;
    tmp = people[Large];
    people[Large] = people[k];
    people[k] = tmp;
    this method compiles but i need to sort the birthday and dont know how. Also i need to output the whole array in birthday order.
    Any help would be very greatful.
    Thanks
    Dave

    Hi,
    If my understanding is right..
    You are trying to sort with birthday as the primary sort criterria.
    For doing that, you have to write the comparison logic inside the compareTo() method implemented in the Person class (Inherited from Comparable Interface).
    i.e. The compareTo() method should use the the primary_sort_variable(here it is birthday or something derived from it) to return a boolean value for your need.

  • AAAGGGHH!!! Selection sort with external file!

    Hi, i am trying to sort marks from an external file in ascending order, using a selection sort via an existing class StudentMark.
    However, i am receiving 1 error when i compile it!!!!
    code below:
    import java.io.*;
    import java.util.*;
    class sort
         // method to display the contents of an array
         static StudentMark data[];
         static void displayData(int[] data)
              try
                   data = StudentMark.loadMarks();
                   for (int index=0; index != data.length; index++)
                        System.out.println(data[index]+"\t");
              catch(Exception e)
                   System.out.println(e.getMessage());
         static int positionOfLargest(int[] data, int limit)
         // method to return the position of the largest item
         // in the data with bounds 0..limit
              int largest = data[0];
              int indexOfLargest = 0;
              for (int index=1; index <= limit; index++)
                   if (data[index]> largest)
                        largest = data[index];
                        indexOfLargest = index;
              return indexOfLargest;
         public static void selectionSort(int[] data)
         // method to sort the contents of an data into ascending order
              int temporary;
              int position;
              int size=data.length;
              for (int index=size-1; index > 0; index--)
                   position=positionOfLargest(data, index);
                   // swap numbers
                   if (index != position)
                        temporary = data[index];
                        data[index] = data[position];
                        data[position] = temporary;
         public static void main(String[] args)
              int[] data;
              System.out.println("numbers before being sorted\n");
              displayData(data);
              selectionSort(data);
              System.out.println("numbers after being sorted\n");
              displayData(data);
    the error is: sort.java:14: incompatible types -                data = StudentMark.loadMarks();
    ^
    Can anyone see what i am doing wrong??
    Thanks!!

    static StudentMark data[];
    data = StudentMark.loadMarks();the error message "incompatible types" means that the type of data and the return type of StudenMark.loadMarks() are not compatible.
    in case of we don't know the return type of StudentMark.loadMarks() i could only guess:
    class StudentMark {
      public static StudentMark[] loadMarks() {
    }if you used that kind of method declaration you should change your declatation of the variable data:
    public static StudentMark[] data;then your codeline 14 shouldn't be a problem any longer.
    StudentMark[] data and StudentMark data[] ARE different!
    hope it helps.

  • Recursive selection sort stack overflow

    hi, first time posting here.
    i have to write a java method that implements a selection sort. This method must be recursive. ok not a problem. i have come up with this so far
        public int findMin(int index) {
            int min = index - 1;
            if (index < num.length - 1) min = findMin(index + 1);
            if (num[index] < num[min]) min = index;
            return min;
        public void selectionSort(int left) {
            if (left < num.length - 1) {
                swap(left, findMin(left));
                selectionSort(left + 1);
        public void swap(int index1, int index2) {
            int temp = num[index1];
            num[index1] = num[index2];
            num[index2] = temp;
        }which works fine until i toss in a lot of values into the array. this creates a stack overflow, and ive been told that i need to use the divide and conquer method of resolving this issue. I guess this means to split the array up and sort each half seperatly, again and agin, or so im told.
    My question is how do i go about doing this, i am at a loss. Any help at all would be great.
    thank you
    lance

    i get this when i push the array passed about 5500 in sizeI got no problem. Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html
    It is silly to implement selection sort with recursion, double-silly if you use double-recursion as your current code.
    /* silly but no OOME when used against 5500 element array */
    import java.util.*;
    public class RecursiveSelectionSort{
      static int[] num;
      public static int findMin(int index) {
        int min = index; // your code had a bug here
        if (index < num.length - 1){
          min = findMin(index + 1);
        if (num[index] < num[min]){
          min = index;
        return min;
      public static void selectionSort(int left) {
        if (left < num.length - 1) {
          swap(left, findMin(left));
          selectionSort(left + 1);
      public static void swap(int index1, int index2) {
        int temp = num[index1];
        num[index1] = num[index2];
        num[index2] = temp;
      public static void main(String[] args){
        Random rand = new Random();
        int n = 10;
        if (args.length > 0){
          n = Integer.parseInt(args[0]);
        num = new int[n];
        for (int i = 0; i < num.length; ++i){
          num[i] = rand.nextInt(10000);
        selectionSort(0);
        for (int in : num){
          System.out.print(in + " ");
        System.out.println();
    }

  • Using Comparator to sort an array

    I didn't undersatnd why a comparator is used for sorting an arry in ascending order
    For descending also i didn't understand the logic it follows
    I have a program which works for both asc and desc using comparator
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    can anyone explain
    1 why do we are passing an object of Ascend class(code was there in above program) to Arrays.sort() method
    2. what will be retruned by that object
    3 why do we are passing an object of Descend class(code was there in above program) to Arrays.sort() method
    4. what will be retruned by that object
    5 We can sort the array in ascending simply by using Arrays.sort(arr) method directly, then what was usage of Ascend class
    If I am wrong in understating the code of the above pls correct me and tell me the actual usage of Comparator<T> interfance and its method compare()
    Pls....

    camickr wrote:
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.am sorry!! pls find the code and try to execute it. It works fine in sorting
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    Can u explain the below
    what happens actually when Arrays.sort(arr,new Descend() ) is executed

  • JTable woes (JDK 1.5): Sorting and updating data

    So I've been working on this project for a while here that is essentially the front-end to a database system. The data itself is displayed in a JTable derivative. Column 1 is a JComboBox containing a list of companies, Column 2 is a JComboBox containing a list of employees, and the rest of the columns contain information specific to that employee.
    The data for each row is actually contained within a custom TableRowData object, which is used to assign listeners and such:
        private void initComponents() {
            this.organizations.setSelectedEnum(this.data.getOrganizationNumber());
            organizations.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        clearData();
                        try {                 
                            updateEmployees();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
            pocs.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {               
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        try {
                            data = getEmployeeInformation();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
        }Ideally, I would like a change in Column 1 to load the employees for the selected company into Column 2. This is working as expected.
    I would also like a change in Column 2 to load the information specific to the selected employee into the rest of the columns. This is also working as expected.
    The problem I am having arises when the data is sorted and THEN a change is made to either column.
    To sort, I am using a custom comparator that keeps track of the sort direction and current sort column.
    In the JTable derivative class, I have a method, sortByColumn(int col):
    public void sortByColumn(int col) {
            this.getColumnModel().getColumn(col).getCellEditor().cancelCellEditing();
            if(this.getSelectedRow() > 0 && this.getSelectedRow() < this.getRowCount())
                this.removeRowSelectionInterval(this.getSelectedRow(), this.getSelectedRow());
            DefaultTableModel mdl = (DefaultTableModel)this.getModel();
            comp.setSortColumn(col);
            Collections.sort(mdl.getDataVector(), comp);
            // Declare and initialize the header
            JTableHeader header = this.getTableHeader();
            // Reset all headers to their identifier values
            for(int i = 0; i < mdl.getColumnCount(); i++) {
                String identifier = header.getColumnModel().getColumn(i).getIdentifier().toString();
                header.getColumnModel().getColumn(i).setHeaderValue(identifier);
            // Find the sort order (for the sorting indicator)
            int sortOrder = comp.getSortOrder(col);
            // Store the identifier text temporarily
            String headerText = header.getColumnModel().getColumn(col).getIdentifier().toString();
            // Declare and initialize the sort indicator based on the sort order
            String sortIndicator;
            switch(sortOrder) {
                case TableRowComparator.ASCENDING:
                    sortIndicator = "  \u2191";
                    break;
                case TableRowComparator.DECENDING:
                    sortIndicator = "  \u2193";
                    break;
                case TableRowComparator.UNSORTED:
                    sortIndicator = "";
                    break;
                default:
                    sortIndicator = "  \u2193";
                    break;
            /* Set the Header to display the text with the indicator. Since
             * this will automatically set the Identifier to the same value,
             * reset it to the value we stored previously.
            header.getColumnModel().getColumn(col).setHeaderValue(headerText+sortIndicator);
            header.getColumnModel().getColumn(col).setIdentifier(headerText);
            // Make sure all the changes are painted
            header.repaint();
            this.repaint();
        }After the sort, the rows are updated and displayed correctly. However, for example with three rows, if by sorting row 1 and row 3 swap, changing the JComboBox in row 3 also updates the data in row 1.
    I'll be converting my code into a short self-contained program momentarily to post on here for a better understanding of what's going on. However, I decided I would post this just in case there were something painfully obvious I missed.
    Thanks.

    Thanks, you've been really helpful :) However, I realized while trying to copy my code to a smaller, self-contained form to illustrate my problems... I never changed the row number in my TableDataRow! So of course the update information, which was relying on the row number stored in the TableDataRow object (and not the actual row number in the model's data vector) updated according to the old row numbers.
    Basically, I coded myself into a corner :P
    Fixed it by making a new comparator to compare TableDataRow objects, and I stored an array of those objects in my custom table model. So the hard work is done on the TableDataRow objects, the data vector is cleared, and then each TableDataRow is added back as a vector.
    Not sure if this is the most elegant solution, but... it works.
    Edited by: GranoblasticMan on Oct 21, 2008 1:11 PM

  • Help needed badly for selection sort

    I posted this on the other forum but haven't gotten a reply. I have a class that compares the zip codes of a file that is read into the code and store as objects. Now I have to sort the information by the zip codes this is what I have so far and I do not know what I am doing wrong with the selection sort. This is the first time I am doing selection sort.
    Here is my .txt
    10
    Dillin Jake York PA 17409
    Valdir John Chicago IL 98098
    Morphy Bob Harrisburg PA 73829
    Spears Johnathan Chicago IL 09182
    Simpson Bloo Los Angeles CA 94840
    Griffin Taylor York IL 49283
    Cartmen Eric Philadelphia PA 28192
    Connaly Teds Springfield IL 12930
    Marsh Stan Miami FL 48392
    William Thomas Reno NV 39029
    and this is the code:
    import java.util.*;
    import java.io.*;
    import java.util.Scanner.*;
    public class TestCustomer6 {
      public static void main (String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner (new File ("customerData.txt"));
        int numLines = scan.nextInt();
           Customer2[] customer;
         customer = new Customer2[40];
        for (int i = 0; i < numLines; i++) {
          String fName = scan.next();
          String lName = scan.next();
          String city = scan.next();
          String state = scan.next();
          int zip= scan.nextInt();
         Customer2 newObj = new Customer2(fName,lName,city,state,zip);
        customer=newObj;
    public static void selectionSort(int[] array)
    {int count;
       for (count = 0; count < array.length; count++)
          int indexOfMin = findMinimum (array, count);
           swap (array, count, indexOfMin );
         public static int findMinimum (int[] array, int startIndex)
    {int mycount;
         int indexOfMin = startIndex;
           for(mycount = startIndex + 1; mycount < array.length; mycount++)
              if (array[mycount] < array[indexOfMin]
    indexOfMin = mycount;
    return indexOfMin;
         public static void swap (int[] array, int preIndex, int nexIndex)
    double temp = array[preIndex];
    array[nexIndex] = array[preIndex];
    array[nexIndex] = temp;
    the class:
    import javax.swing.*;
    class Customer2{
        public static final int FNAME = 0;
        public static final int ZIP = 1;
        private static final int LESS = -1;
        private static final int EQUAL = 0;
        private static final int MORE  = 1;
        private static int compareAttribute;
         private String firstName;
         private String lastName;
         private String city;
         private String state;
         private int zip;
        static {
           compareAttribute = FNAME;
         public Customer2(){
         firstName = " ";
         lastName = " ";
         city = " ";
         state = " ";
         zip = 0;
         public Customer2(String f, String l, String c, String s, int z){
              this.firstName = f;
              this.lastName = l;
              this.city = c;
              this.state = s;
              this.zip = z;
              System.out.println(this.toString());
        public static void setCompareAttribute( int attribute ) {
            compareAttribute = attribute;
        public int compareTo( Customer customer, int attribute ) {
            int comparisonResult;
            if ( attribute == ZIP ) {
                int p2zip = customer.getZip( );
                if (this.zip < p2zip) {
                    comparisonResult = LESS;
                } else if (this.zip == p2zip) {
                    comparisonResult = EQUAL;
                } else {
                    assert this.zip > p2zip;
                    comparisonResult = MORE;
            } else { //compare the name using the String class�s
                    //compareTo method
                String    p2fname = customer.getFirst( );
                comparisonResult = this.firstName.compareTo(p2fname);
            return comparisonResult;
        public int compareTo( Customer customer ) {
            return compareTo(customer, compareAttribute);
         public String getFirst(){
              return firstName;
         public String getLast(){
              return lastName;
         public String getCity(){
              return city;
         public String getState(){
              return state;
         public int getZip(){
              return zip;
         public String toString(){
              return  getFirst() + ",  " + getLast() + "     " + getCity() + "     "
              + getState() + "     " + getZip();

    1) Your code doesn't compile;
    2) You don't call your selection sort method anywhere;
    3) Your selection sort attempts to sort an int array which doesn't make sense;
    4) You don't use the comparison methods defined in your Customer2 class;
    5) I think that you've just copied/pasted several code fragments;
    6) Your indentation style is highly inconsistent (also see 5).
    kind regards,
    Jos

  • HT201303 was just having this problem until today. It is now all sorted and I can explain what to do very simply and easily.

    I was just having this problem until today. It is now all sorted and I can explain what to do very simply and easily.
    I remembered the answers to my questions, I just forgot "EXACTLY" how I entered the text - so I had to have them reset. The easiest way is to sign in through www.appleid.com. Then on the right click the "Manage your Account" link and sign in. Easy so far right. Then, as others have said, look on the left of the screen you will see a link called "Password and Security" - click on this. Now this is where the confusion begins. Some people have a link located directly under the existing questions that looks like this "Forgot your answers? Send reset security info email to blah blah blah email . If you see this click it and it will send an email to the "Rescue Email" address that you entered when you originally entered your answers. Follow the instructions contained in this email and you are done. If you cannot remember this email address or you have since closed it, you will need to go to the Itunes Express lane and send an email to Apple requesting them to reset your answers.
    HOWEVER IF YOU DO NOT SEE A THIS LINK UNDER THE QUESTIONS - this means that you DID NOT enter a Rescue email address when you originally set your questions. The only way you can now reset your Security Questions and Answers is to go to the Itunes Express lane and email Apple asking to have these reset. I have 2 apple accounts, one for myself and one for my daughter - as I did not include a rescue email I had to email apple. On both occasions, these questions were reset and an email sent to me exactly 24 hours after I sent them the request. I entered the new details, WROTE THEM DOWN EXACTLY AS I ENTERED THEM THIS TIME, entered a Rescue Email this time and I am good to go again. Simple. Now when I log in and click on "Password and Security" I do have the reset link visable. Apple support are good, they just take a bit of time to get things done, but they always seem to get there in the end. I just wish someone had taken the time to explain this somewhere else in the forum as it would have saved me much time and angst.
    To get to the Itunes Express Lane go to this website www.appleid.com make sure the correct country is displayed top right, if not change it. Once this is saved go to the tabs at the top of the screen and click Support. Then halfway down the next page you will see a photo of two random people with a title of Contact Apple Support - Click this. Scroll down until you see the itunes logo, to the right of this you will see the link Express Lane for iTunes Player and iTunes Store - click on this. One the right hand side of the next page click on the link "itunes Store". On the next page click the link "Account Management" check the radio button beside "itunes store account security", select your country from the drop down box and click "Continue". Under the heading MORE OPTIONS, you will see a clickable link called email - click this. Fill in your name, Apple ID and country. Then in the text box, write "I have forgotten the answers to my Security questions, would you kindly please reset them. Thank-You". Then Click Continue, you will be given a reference number and an email is sent to your address advising that generally someone will attend to your request within 24 hours. Like I said previously, I had to do this twice and both times it was reset however it was done within about 5 minutes of the 24 hour cut off, so you will have to be patient. I know 100% that this works for Australia - I am guessing other countries should be similar. Hope this helps someone somewhere!

    Standard troubleshooting...
    1. Try a Restart by pressing the sleep/lock button until you see the slider.  Slide to power off.  Restart by pressing the sleep/lock button until you see the Apple logo.
    2. Try a Reset by pressing the home and sleep buttons until you see the Apple logo, ignoring the slider if it comes up. Takes about 5-15 secs of button holding and you won't lose any data or settings.
    3. Remove apps from Recently Used list...
    - From any Home Screen, double tap the home button to bring up the Recents List
    - Swipe up on the app preview card
    - Press the home button when done.
    4. If still a problem restore with your backup.
    5. If still a problem restore as new, i.e. without your backup. See how it runs with nothing synced to it.
    6. If still a problem, it's likely a hardware issue.

  • Sorting and Grouping in Projects View

    In Projects view, when either of two of the three grouping options is selected, there are two sorts in effect: the groups themselves are sorted, and the contents of each group are sorted. These sorts are handled differently, depending on the grouping selected and the sort order selected.
    (It appears that there is a bit of the old Apple voodoo in here. The results are arbitrary , but they seem to have been carefully chosen to meet most users expectations. That is to say -- and this is an Apple programming trait -- the arbitrariness is faithful to the expected users' needs, not to logic.)
    There are four sorts available, and three groupings
    Sorts:
    . Name
    . Date -- Oldest First
    . Date -- Newest First
    . Library
    Groupings:
    . Ungrouped
    . Group by year
    . Group by folder
    So that's twelve possible ways to display Projects in Projects view.
    Let's look at a few of them. I'm going to refer to the groups as "Year groups" or "Folder groups" and to the contents of the groups as "Projects". So there is sorting of the groups, and sorting of the contents of the groups (same as "within the group"). These I'll refer to as "Groups sorting" and "Projects sorting".
    Sort: Date -- Newest First
    Grouping: Group by Year
    Result: Year groups are sorted in the same order as Projects. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together.
    Sort: Date -- Oldest First
    Grouping: Group by Year
    Results are as expected; a reversal of the "Newest First" sort, but with the same groups: Year groups are sorted in the same order as Projects. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together.
    Sort: Name
    Grouping: Group by Year
    Result: Year groups are sorted by year, oldest first. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together. Projects are sorted alphabetically, descending.
    Sort: Library
    Grouping: Group by year
    Result: Year groups are sorted by year, oldest first. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together. Projects are listed in the order they occur in the Library structure shown on the Library tab of the Inspector. (Note that this last is literal: a Project named "Aardvark Close-ups" if it's in a Folder named "Zoography" will be listed after all the projects in "Yellow Paintings" and all the Projects in "X-rays, thoracic" if those Projects are in alphabetical order by Folder name in the Library. You can see all the Projects in your Library listed on the Library tab of the Inspector by "{Option}+clicking" the disclosure triangle next to "PROJECTS & ALBUMS" twice.)
    Sort: Date - Newest First
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted by date, newest first. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder.
    Sort: Date - Oldest First
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted by date, oldest first. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are sorted alpha-name, descending).
    Sort: Name
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted alphabetically by name, descending. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are sorted alpha-name, descending).
    Sort: Library
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are listed in the order they occur in the Library structure shown on the Library tab of the Inspector (see note above). Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are listed in the order they appear in the Library).
    Ernie [asked:|http://discussions.apple.com/thread.jspa?threadID=2816124&tstart=0]
    +I see those icons but note that those projects in folders will be in different sections arranged alpha, and then date within. Am I correct on that?+
    The answer is, it depends.
    If "Group by year" is selected, the Groups-sorting will always be by date, regardless of the sort order specified. The Groups-sorting order will follow whatever is specified for the Projects sort order (or default to "oldest first").
    If "Group by folder" is selected, the Groups-sorting will always be alphabetical, descending, regardless of the sort order specified. (So if you use Projects view, take care in naming your Folders. Use prefixes if needed to force a desired alpha sort.)
    If "Ungrouped" is selected, there are no Groups and perforce no Groups-sorting.
    That's all I have to say on this topic (today).
    Message was edited by: Kirby Krieger

    In Projects view, when either of two of the three grouping options is selected, there are two sorts in effect: the groups themselves are sorted, and the contents of each group are sorted. These sorts are handled differently, depending on the grouping selected and the sort order selected.
    (It appears that there is a bit of the old Apple voodoo in here. The results are arbitrary , but they seem to have been carefully chosen to meet most users expectations. That is to say -- and this is an Apple programming trait -- the arbitrariness is faithful to the expected users' needs, not to logic.)
    There are four sorts available, and three groupings
    Sorts:
    . Name
    . Date -- Oldest First
    . Date -- Newest First
    . Library
    Groupings:
    . Ungrouped
    . Group by year
    . Group by folder
    So that's twelve possible ways to display Projects in Projects view.
    Let's look at a few of them. I'm going to refer to the groups as "Year groups" or "Folder groups" and to the contents of the groups as "Projects". So there is sorting of the groups, and sorting of the contents of the groups (same as "within the group"). These I'll refer to as "Groups sorting" and "Projects sorting".
    Sort: Date -- Newest First
    Grouping: Group by Year
    Result: Year groups are sorted in the same order as Projects. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together.
    Sort: Date -- Oldest First
    Grouping: Group by Year
    Results are as expected; a reversal of the "Newest First" sort, but with the same groups: Year groups are sorted in the same order as Projects. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together.
    Sort: Name
    Grouping: Group by Year
    Result: Year groups are sorted by year, oldest first. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together. Projects are sorted alphabetically, descending.
    Sort: Library
    Grouping: Group by year
    Result: Year groups are sorted by year, oldest first. Projects which span multiple years are put in multi-year groups. Projects with the same spans are grouped together. Projects are listed in the order they occur in the Library structure shown on the Library tab of the Inspector. (Note that this last is literal: a Project named "Aardvark Close-ups" if it's in a Folder named "Zoography" will be listed after all the projects in "Yellow Paintings" and all the Projects in "X-rays, thoracic" if those Projects are in alphabetical order by Folder name in the Library. You can see all the Projects in your Library listed on the Library tab of the Inspector by "{Option}+clicking" the disclosure triangle next to "PROJECTS & ALBUMS" twice.)
    Sort: Date - Newest First
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted by date, newest first. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder.
    Sort: Date - Oldest First
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted by date, oldest first. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are sorted alpha-name, descending).
    Sort: Name
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are sorted alphabetically by name, descending. Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are sorted alpha-name, descending).
    Sort: Library
    Grouping: Group by folder
    Result: Folder groups are sorted alphabetically by name, descending. Projects are listed in the order they occur in the Library structure shown on the Library tab of the Inspector (see note above). Clicking a Folder's name in the Project viewer drills down to show the sub-Folders and Projects in the clicked Folder (where, again, Folder groups are sorted alpha-name, descending, and Projects are listed in the order they appear in the Library).
    Ernie [asked:|http://discussions.apple.com/thread.jspa?threadID=2816124&tstart=0]
    +I see those icons but note that those projects in folders will be in different sections arranged alpha, and then date within. Am I correct on that?+
    The answer is, it depends.
    If "Group by year" is selected, the Groups-sorting will always be by date, regardless of the sort order specified. The Groups-sorting order will follow whatever is specified for the Projects sort order (or default to "oldest first").
    If "Group by folder" is selected, the Groups-sorting will always be alphabetical, descending, regardless of the sort order specified. (So if you use Projects view, take care in naming your Folders. Use prefixes if needed to force a desired alpha sort.)
    If "Ungrouped" is selected, there are no Groups and perforce no Groups-sorting.
    That's all I have to say on this topic (today).
    Message was edited by: Kirby Krieger

Maybe you are looking for

  • How to publish my website using iWeb ? Other than FTP !

    Hello Guys ,                        I want to build my own website and I have iWeb software which I got preinstalled when I purchased my MBP. As Mobile me is out of service could anyone give an alternative way to publish my website. I have seen some

  • Correlations in SAP Business Workflow

    Dear folks, i wanted to check out correlations in Workflow so i tried to follow the step by step blog of Phil: Correlations in SAP Business Workflow But this doesn't work for me, cuz everytime the workflow ends up with an error: Workflow '00000000105

  • Photoshop CS4 ChangeColorSettings

    I am writing a VB script for Photoshop CS4 and I am trying to change the default color settings from within the script.  <br /><br />However it keeps failing with the following message:  "General Photoshop error occurred. This functionality may not b

  • Lightroom v5.7 Upgrade - Where is it?

    Clicked on Lightroom's "Download" button from the pop-up, but it takes me to the Adobe splash screen.  Where is the v5.7 update download???? Facial Recognition – Quickly find and organize your friends and family. HDR Merge – Combine multiple photos t

  • [SOLVED] Unable to net-start "default" network in libvirt (KVM)

    Hi. I've used this tutorial  and have net-define'ed a network from this xml, but when i try to net-start it, i get the following error: virsh # net-start default error: Failed to start network default error: internal error Network is already in use b