1

This is the text file:

1,2,8,4,5,6,7,7,

3,4,5,6,7,8,

5,6,7,8,9,9,

1,2,3,4,5,8,9,0

After ignoring the 1st column:

2,8,4,5,6,7,7,

4,5,6,7,8,

6,7,8,9,9,

2,3,4,5,8,9,0

I want to sort the array in descending order but I can't get it to work. This is the code that I have done so far:

Scanner scanner = new Scanner(new File("test.txt"));

int row = 0;
int col = 0;

while (scanner.hasNextLine())
{
    String currentline = scanner.nextLine();

    row++;

    String[] items = currentline.split(",");
    int[] intitems = new int[items.length];

    for (int i = 1; i < items.length; i++)
    {
        intitems[i] = Integer.parseInt(items[i]);

        System.out.print(intitems[i] + " ");

        int temp = 0;
        for (int j = 2; j < (items.length - i); j++)
        {
            temp = intitems[j - 1];
            intitems[j - 1] = intitems[j];
            intitems[j] = temp;
        }
        col = i;
    }

    col++;
    System.out.println();
    System.out.println("After sort: " + intitems);

    System.out.println();
}

System.out.println("Row: " +row);
3
  • My bad, i accidentally tag javascript. Sry Commented Sep 29, 2014 at 9:18
  • Does the kind of sorting algorithm matter? Commented Sep 29, 2014 at 9:26
  • It does not matter as long as it is easy to understand. Commented Sep 29, 2014 at 9:32

5 Answers 5

4

No need to complicate things:

for (int i = 1; i < items.length; i++) {
  intitems[i - 1] = Integer.parseInt(items[i]);
}

Arrays.sort(intitems); // Ascending
Arrays.sort(intitems, Collections.reverseOrder()); // Descending

But if you really want to use a loop to sort the array (bubblesort) you need to compare the items you switch:

for (int i = 0; i < intitems.length - 1; i++) {
  for(int j = i + 1; j < intitems.length; j++) {
    if (intitems[i] > intitems[j]) {
      int temp = intitems[j];
      intitems[j] = intitems[i];
      intitems[i] = temp;
    }
  }
}

If you want it sorted in descending order then just change the greater than (>) comparison to a lesser than (<) comparison:

    if (intitems[i] < intitems[j]) {
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't help at all, he clearly wants to master a sorting algorithm, not to use a built-in function that any dumb can use.
Please mention which sorting algorithm you are using :P
In this coding, I am using bubble sort algorithm but i cant get it to work correctly.
@Dici: Nowhere in the OP does it state that he/she wants to master a sorting algorithm. The OP only says he/she wants the array sorted.
1
private static void sortInDescending(int[] arrayObj) 
    {           
        int n = arrayObj.length;
        int temp = 0;

        for(int i=0; i < n; i++)
        {
            for(int j=1; j < (n-i); j++)
            {                                   
                if(arrayObj[j-1] < arrayObj[j])
                {
                    temp = arrayObj[j-1];
                    arrayObj[j-1] = arrayObj[j];
                    arrayObj[j] = temp;
                }                         
            }
        }   
    }

Call method

 sortInDescending(arrayinput);

Comments

1

You can use the Arrays.sort() with a custom comparator to make it descending.

    String[] items = currentLine.split(",");
    Integer[] intItems = new Integer[items.length];

    for(int i=0; i<intItems.length; ++i) {
        intItems[i] = Integer.parseInt(items[i]);
    }

    Comparator<Integer> comparator = new Comparator<Integer>() {
        @Override
        public int compare(Integer left, Integer right) {
            return -Integer.compare(left, right);
        }
    };

    Arrays.sort(intItems, comparator);

    System.out.println(Arrays.toString(intItems));
}

Or you can sort the array in ascending order and reverse the array.

    Arrays.sort(intItems);

    Integer[] descending = new Integer[intItems.length];

    int length = descending.length;
    for(int i=0; i<length; ++i) {
        descending[i] = intItems[length - 1 - i];
    }

    System.out.println(Arrays.toString(descending));

Comments

1

Other answers contain the bubble sort algorithm, where one element is compared to its successor. If the sort condition matches, then they get swapped. A slightly faster solution is insertion sort: in essence, it finds the maximal (minimal) value of the array and puts it to the front. There the implementation could look like this:

static int[] array = {2,8,4,5,6,7,7,};


public static void insertionSort(final int[] array) {       

    for(int i = 0; i < array.length; i++){
        int maxValueIndex = findMaxValue(array, i);

        int temp = array[i];
        array[i] = array[maxValueIndex];
        array[maxValueIndex]=temp;
    }
}

private static int findMaxValue(final int[] array, int index) {

    int value = Integer.MIN_VALUE;

    for (int i = index; i < array.length; i++) {

        if (array[i] > value) {
            value = array[i];
            index = i;
        }
    }
    return index;
}

public static void main(final String[] args){
    insertionSort(array);
    System.out.println(Arrays.toString(array));
}

Comments

1

There you go :

 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;

 public class SortTXT {

static File fout;

public static void main(String[] args) {

    fout = new File("text.txt");
    if (!fout.isFile()) 
    {
        System.out.println("text.txt - Parameter is not an existing file");
    }
    else
    {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fout)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                if (line.length()>2)
                {
                    line.trim();
                    // crete an array from the line - seperate by ","
                    List<String> list = new ArrayList<String>(Arrays.asList(line.split(",")));
                    // remove the 1st number
                    list.remove(0);
                    //sorting the list
                    Collections.sort(list);
                    System.out.println();
                    System.out.println("After sort: ");

                    // print out the sorted array
                    for(String temp: list){
                        System.out.print("," + temp);
                }
            }
            }
        } catch (IOException e) {
        }

        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

Hope This Helps :)

Dave.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.