Sort Array in Descending order in Java [duplicate] - java

This question already has answers here:
Java Array Sort descending?
(27 answers)
Closed 5 years ago.
This array Sorts the number in Ascending and prints the output. I wanna change it to descending, but i can't figure it out.. i tried changing the + to - but it didn't seem to work.. Can someone tip me on how to do it?
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int smallestIndex;
int minIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
smallestIndex = index;
for (minIndex = index + 1;
minIndex < listLength; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}

I suggest you look up articles on "bubble sort", which is fairly close to what you are doing here. Then, follow up with learning how other sort algorithms work. You generally do not want to use an n-squared sort algorithm.
To do the sort in the reverse order, you would want to use the smallestIndex variable to store the largest index instead. Change the name there, and use the > operator on the line if (list[minIndex] < list[smallestIndex]) to find the biggest number. You will then be storing the largest number in the first list position and the smallest in the last list position.
The updated loops would look like:
for (index = 0; index < listLength - 1; index++)
{
biggestIndex = index;
for (minIndex = index + 1; minIndex < listLength; minIndex++)
if (list[minIndex] > list[biggestIndex])
biggestIndex = minIndex;
temp = list[biggestIndex];
list[biggestIndex] = list[index];
list[index] = temp;
}

A simple way to modify this code to sort array in descending order is to change the comparison operator from smaller than (<) to larger than (>).
Your code:
if (list[minIndex] < list[smallestIndex])
Change to:
if (list[minIndex] > list[smallestIndex])
You should also change the variable naming otherwise it does not make sense.

It sounds like you want a "for loop" to run in reverse:
for (i = listLength; i>0; i--) {
System.out.print(list[i] + ",");
}
You need to start with
list[listLength]
and increment down until you get to the beginning of the list/array which is
list[0].

I just made a few modifications. Changed the variable name and the important part
if (list[maxIndex] > list[largestIndex]) // changed less than sign to greater than
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int largestIndex;
int maxIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
largestIndex = index;
for (maxIndex = index + 1;
maxIndex < listLength; maxIndex++)
if (list[maxIndex] > list[largestIndex])
largestIndex = maxIndex;
temp = list[largestIndex];
list[largestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}

Related

Garbage Value Picked Up by Scanner -- Java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 months ago.
I am trying to sort an array in descending order. The size of the array comes from user input, and then the contents of the array come from user input. Then the array is passed to a function that sorts it. The issue is that, instead of printing a sorted array, it prints [I#5caf905d. Through print statements, I have pinpointed the problem to the scanner picking up [I#5caf905d as the final value from user input, coming right after all the correct inputs. I don't know where this value came from, and I also don't understand why it is printed by the function as if it were the entire array. All help is appreciated!
Here is my code. Input is: 5 10 4 39 12 2.
import java.util.Scanner;
public class LabProgram
{
public static void sortArray (int [] myArr, int arrSize)
{
int temp;
int i;
for (i = 0; i < arrSize - 1; i++)
{
if (myArr[i] < myArr[i + 1])
{
temp = myArr[i];
myArr[i] = myArr[i + 1];
myArr[i + 1] = temp;
}
}
System.out.println(myArr);
}
public static void main(String[] args)
{
Scanner scnr = new Scanner (System.in);
int [] myArr;
int arrSize;
int i;
arrSize = scnr.nextInt();
myArr = new int[arrSize];
for (i = 0; i < arrSize; i++)
myArr[i] = scnr.nextInt();
sortArray (myArr, arrSize);
}
}
You should use one of the simpliest sorting algorithm e.g. Selection Sort:
public static void selectionSortDesc(int[] arr) {
for(int i = 0; i < arr.length; i++) {
// k index with max value
int k = i;
// find k with max value
for(int j = i; j < arr.length; j++) {
if(arr[k] < arr[j])
k = j;
}
// swap current element with the max value
swap(arr, i, k);
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = arr[i];
}
By the way, you should not mix sorting and printing the array. It's better to split these parts.

Make Bubble Sorting more Efficient

I have the code for bubble sorting down below. I was wondering how I would be able to run more efficient and loop less amount of times
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
Any help would be greatly appreciated. I am new to coding and have been very stumped on how to improve efficiency and have it loop less times.
Bubble sort is an inefficiency sorting algorithm and there are much better sorting algorithm.
You can make a bubble sort more efficient, its called Optimized Bubble Sort (It is still quite inefficient)
Optimized bubble sort in short is, - you pass n times , but on the every iteration you 'bubble' the biggest (or smallest) element to the end of the array. Now that last item is sorted, so you don't have to compare it again.
I wrote this code last year, not to sure if it still works:
public static void bubbleSort_withFlag(Integer[] intArr) {
int lastComparison = intArr.length - 1;
for (int i = 1; i < intArr.length; i++) {
boolean isSorted = true;
int currentSwap = -1;
for (int j = 0; j < lastComparison; j++) {
if (intArr[j] < intArr[j + 1]) {
int tmp = intArr[j];
intArr[j] = intArr[j + 1];
intArr[j + 1] = tmp;
isSorted = false;
currentSwap = j;
}
}
if (isSorted) return;
lastComparison = currentSwap;
}
}
Here you can read on optimized bubble sort
Here you can find a list of different sorting algorithms that could be more efficient depending on your scenario.

How do I remove the item with the highest value in an unsorted array?

So right now I am trying to code a function that will remove the highest value in an unsorted array.
Currently the code looks like this:
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
}
/*int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}*/
}
tailIndex = tailIndex - 1;
}
Here I have my attempt at this:
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
The program runs no bother but still deletes the first item in the array instead of the highest number. This code was given my my college lecturer for a different solution but unfortunately it doesn't work here.
Would this solution work with enough altercations? Or is there another solution I should try?
Thanks.
The code snippet in the question can be updated to below code, while keeping the same data structure i.e. queue and this updated code has 3 steps - finding the index of largest element, shifting the elements to overwrite the largest element and finally set the tailIndex to one less i.e. decrease the size of the queue.
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
int largeIndex = 0;
for (int i = 0; i < tailIndex; i++) {
if (((PriorityItem<T>) storage[i]).getPriority() > priority) {
priority = ((PriorityItem<T>) storage[i]).getPriority();
largeIndex = i ;
}
}
for(int i = largeIndex; i < (tailIndex - 1) ; i++)
storage[i] = storage[i + 1];
}
tailIndex = tailIndex - 1;
}
Hope it helps.
Step 1
Find the highest index.
int[] array;
int highIndex = 0;
for (int i = 1; i < highIndex.size(); i++)
if (array[highIndex] < array[highIndex])
highIndex = i;
Step 2
Create new array with new int[array.size() - 1]
Step 3
Move all values of array into new array (except the highest one).
My hint: When its possible, then use a List. It reduces your complexity.
You can find the largest Number and it's index then copy each number to its preceding number. After that, you have two options:
Either add Length - 1 each time you iterate the array.
Or copy the previous array and don't include removed number in it.
Working Code:
import java.util.Arrays;
public class stackLargest
{
public static void main(String[] args)
{
int[] unsortedArray = {1,54,21,63,85,0,14,78,65,21,47,96,54,52};
int largestNumber = unsortedArray[0];
int removeIndex = 0;
// getting the largest number and its index
for(int i =0; i<unsortedArray.length;i++)
{
if(unsortedArray[i] > largestNumber)
{
largestNumber = unsortedArray[i];
removeIndex = i;
}
}
//removing the largest number
for(int i = removeIndex; i < unsortedArray.length -1; i++)
unsortedArray[i] = unsortedArray[i + 1];
// now you have two options either you can iterate one less than the array's size
// as we have deleted one element
// or you can copy the array to a new array and dont have to add " length - 1" when iterating through the array
// I am doing both at once, what you lke you can do
int[] removedArray = new int[unsortedArray.length-1];
for(int i =0; i<unsortedArray.length-1;i++)
{
System.out.printf(unsortedArray[i] + " ");
removedArray[i] = unsortedArray[i];
}
}
}
Note: Use List whenever possible, it will not only reduce complexity, but, comes with a very rich methods that will help you a big deal.

Sort an Array - recursive call

I am writing code to sort an array in order. I checked some algorithm for sort and merge, however I found that if I just go through the array and compare every 2 elements and swap them and repeat that until the array is sorted.
So if array[I] > array[i++], swap, repeat.
It is not working so far. I also need a break point to avoid stack overflow: I need some help please
Array:
int[] newArray = new int[] {3,9,5,7,4,6,1};
SortArray s = new SortArray();
s.sortThisArray(newArray, 0, 0);
Recursive function:
public String sortThisArray(int[] array, double counter, double a)
{
int swap0 = 0;
int swap1 = 0;
if (a > 1000)
{
return "reached the end" ;
}
for (int i =0; i<array.length; i++)
{
if (array[i] > array[i++])
{
swap0 = array[i];
swap1 = array[i++];
array[i++] = swap0;
array[i] = swap1;
counter = counter++;
a = array.length * counter;
sortThisArray (array, counter, a);
}
}
for (int j = 0; j<array.length ; j++)
{
System.out.println(array[j]);
}
return "completed";
}
}
What you are searching for is recursive bubble sort algorithm.
The main error is confusing i++ (which increments i every time) with i+1, that is only the position in the array after i, without incrementing. Then, there is no need to use double for counter, and also the a variable is not needed. You need only the length of the current segment, this way:
import java.util.*;
public class RecursiveBubbleSort {
public static void main(String[] args) throws Exception {
int[] newArray = new int[] {3,9,5,7,4,6,1};
sortThisArray(newArray, newArray.length);
System.out.println("Sorted array : ");
System.out.println(Arrays.toString(newArray));
}
public static int[] sortThisArray(int[] array, int n) {
if (n == 1) {
return array; //finished sorting
}
int temp;
for (int i = 0; i < n-1; i++) {
if (array[i+1] < array[i]) {
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
return sortThisArray(array, n-1);
}
}
The ++ operator evalutes separately. So in the case i++, we will read i and then increment it by 1. And the other way around, ++i, would first apply the increment to i, and then read i. So when you want to check for the next element in the array, [i+1] is what you are looking for. With the same reasoning, can you figure out whats wrong with this line?
counter = counter++;
And do we even need it?

Inplace quick sort

Write a java program to sort a list of integers using ‘in place’ Quicksort algorithm.
Generate the list randomly every time using the java.util.Random class.
Allow the user to choose the size of the array. The program should display the result of sorting the array of that size using different pivot choices. In particular, try these 4 choices –
 First element as pivot
 Randomly choosing the pivot element
 Choosing the median of 3 randomly chosen elements as the pivot
 Median of first center and last element (book technique).
PLEASE dont give me the implementation because I would like to try on my own. I want to know what is inplace quick sort? How is it different from the regular quiksort. Is it regular quicksort. I am really confused. I would like someone to provide the pusedocode or explanation in plain english will help too.
Inplace sorting - it's when you operate on the original array, given to you from outside, as opposed to creating some new arrays and using them in any way. Inplace sorting takes O(1) space, as opposed to O(n)+ when using additional data structres
Example of inplace sort:
public static void simpleBubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[j - 1] > arr[j]) {
swap(arr, j - 1, j);
}
}
}
}
As opposed to Merge sort that creates arrays along the way, and by the end combines them and returns NOT the original (given to us) array, but an array containing the result.
public static int[] mergeSort(int[] arr) {
if (arr.length < 2) return arr;
int mid = arr.length / 2;
int[] left = new int[mid];
int[] right = new int[mid + arr.length % 2];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (i < mid) {
left[i] = arr[i];
} else {
right[j++] = arr[i];
}
}
// keeps going until there's 1 element in each array[]
return mergeReturn(mergeSort(left), mergeSort(right));
}
private static int[] mergeReturn(int[] leftArr, int[] rightArr) {
int leftPointer = 0, rightPointer = 0, combinedSize = leftArr.length + rightArr.length;
int[] merged = new int[combinedSize];
for (int i = 0; i < combinedSize; i++) {
if (leftPointer < leftArr.length && rightPointer < rightArr.length) {
if (leftArr[leftPointer] < rightArr[rightPointer]) {
merged[i] = leftArr[leftPointer++];
} else {
merged[i] = rightArr[rightPointer++];
}
} else if (leftPointer < leftArr.length) { // adding the last element
merged[i] = leftArr[leftPointer++];
} else {
merged[i] = rightArr[rightPointer++];
}
}
return merged;
}

Categories