Jen
Jen

Reputation: 31

Sorting of array

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

Upvotes: 1

Views: 186

Answers (5)

David Gidony
David Gidony

Reputation: 1283

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.

Upvotes: 1

SME_Dev
SME_Dev

Reputation: 1890

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

Upvotes: 1

Sani Huttunen
Sani Huttunen

Reputation: 24385

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]) {

Upvotes: 4

Prateek
Prateek

Reputation: 6975

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

Upvotes: 1

Atuos
Atuos

Reputation: 521

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

Upvotes: 1

Related Questions