Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

sorting array descending order

Design a Java program to

Comments

  • adetola68adetola68 Member Posts: 7
    You are close to the answer. Next time just use a simple sorting algorithm. The simple algorithm sorting method I defined here is called Bubble sort.

    [code]public static void sortDescending(int[] x) {
    int newLowest = 0; // index of first comparison
    int newHighest = x.length-1; // index of last comparison

    while (newLowest < newHighest) {
    int highest = newHighest;
    int lowest = newLowest;

    newLowest = x.length; // start higher than any legal index
    for (int i = lowest; i < highest; i++) {
    if (x[i] < x[i+1]) {
    // exchange elements
    int temp = x[i];
    x[i] = x[i+1];
    x[i+1] = temp;

    if (i newHighest) {
    newHighest = i + 1;
    }
    }
    }
    }
    }[/code]


    Below is the complete listing of the source code

    [code]import java.util.Arrays;
    import java.util.Scanner;

    public class ArraySort {

    public static void main(String [] args) {
    Scanner input = new Scanner(System.in);
    final int SIZE = 6;

    int [] arrayNumber = new int[SIZE];

    // Reading input from keyboard
    for (int i = 0; i < SIZE; i++) {
    System.out.print("Please enter number: ");
    arrayNumber[i] = input.nextInt();
    }

    // Displaying them in the order in which they were input

    for (int i = 0; i < SIZE; i++) {
    System.out.print(arrayNumber[i] + " ");
    }
    System.out.println();

    // Displaying them in reverse order to the order in which they were input
    for (int i = SIZE - 1; i >= 0; i--) {
    System.out.print(arrayNumber[i] + " ");
    }
    System.out.println();

    // Sort and display the integers into ascending order
    Arrays.sort(arrayNumber);

    for (int i = 0; i < SIZE; i++) {
    System.out.print(arrayNumber[i] + " ");
    }
    System.out.println();


    // Displaying them in reverse order to the order in which they were input
    sortDescending(arrayNumber);
    for (int i = 0; i < SIZE; i++) {
    System.out.print(arrayNumber[i] + " ");
    }
    System.out.println();
    }
    public static void sortDescending(int[] x) {
    int newLowest = 0; // index of first comparison
    int newHighest = x.length-1; // index of last comparison

    while (newLowest < newHighest) {
    int highest = newHighest;
    int lowest = newLowest;

    newLowest = x.length; // start higher than any legal index
    for (int i = lowest; i < highest; i++) {
    if (x[i] < x[i+1]) {
    // exchange elements
    int temp = x[i];
    x[i] = x[i+1];
    x[i+1] = temp;

    if (i newHighest) {
    newHighest = i + 1;
    }
    }
    }
    }
    }


    }
    [/code]

    Cheers
Sign In or Register to comment.