JAVA: Sorting an array in descending order - java

I'm trying to sort an array in descending order, I know there are many examples of sorting an array online, but I just wanted to try and do it my own way (just trying to test to see if algorithm could actually work). But some reason, I'm unable to output the array with the result stored, I've tried using System.out.println(Arrays.toString(myList)); and printing them one at time, it works for one the arrays i created, but when trying to modify the array through a loop, it refused to output anything, no error, nothing as though nothing is there. Your help would be appreciated. see code below. Thanks.
import java.util.Arrays;
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
double[] sortedList = new double[7] ;
// Print all the array elements
for (double i: myList) {
System.out.println(i + " ");
}
// Summing all elements
double total = 0;
for (double x: myList) {
total += x;
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
int m, z = 0;
for (double k: myList) {
if (k > max) max = k;
}
do{
for (int i = m; i < myList.length; i++) {
if (myList[i] > max){
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] =0;
m++;
} while(m < myList.length);
System.out.println("Max is " + max);
//System.out.println(Arrays.toString(myList));
for (double y: sortedList) {
System.out.println(y + " ");
}
}
}

you can simply use inbuilt function to sort your array in descending order as
Arrays.sort(myList , Collections.reverseOrder());
System.out.println("myList Array Elements in reverse order:");
for (int i = 0; i < myList .length; i++)
System.out.println(intArray[i]);
It will work for sure.

Your logic for sorting is not working as intended. I have made some changes to it, give it a try :
do {
max = 0;
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] = 0;
m++;
} while (m < myList.length);

The following code works for me.
public class Main {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
double[] sortedList = new double[7] ;
// Print all the array elements
for (double i: myList) {
System.out.println(i + " ");
}
// Summing all elements
double total = 0;
for (double x: myList) {
total += x;
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
int m = 0;
int z = 0;
do{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max){
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] =0;
m++;
max = 0;
} while(m < myList.length);
System.out.println("Max is " + max);
//System.out.println(Arrays.toString(myList));
for (double y: sortedList) {
System.out.println(y + " ");
}
}
}
You're code contained three errors:
1.You failed to reset 'max' in every iteration, leading to 'sortedList'
containing just the value 9.2 in every entry.
for (double k: myList) {
if (k > max) max = k;
}
is unneccessary. Moreover, it doesn't even keep track where the max element is.
3.
for (int i = m; i < myList.length; i++)
should be changed to
for (int i = 0; i < myList.length; i++)
The position you're at in 'sortedList' has nothing to do with where you can
find the maximum element of 'myList'.

First you need to convert this line int m, z = 0; to int m = 0, z = 0;
because int m, z = 0; is equivalent to int m; int z = 0;. Hence when you try to use variable m - it is not initialized yet and that results to a compilation error.
After fixing the above statement, your program will compile and run but there is also a mistake in the program logic as well and your result sorted array will be output as:
{9.2, 9.2, 9.2, 9.2, 9.2, 9.2, 9.2}
as in the following block
for (double k: myList) {
if (k > max) max = k;
}
you initially find the max value which is 9.2 . That's why when you later execute do .. while and check the condition here
if (myList[i] > max){
max = myList[i];
z = i;
}
the statement myList[i] > max will never return true and hence your max will be always remain 9.2 and z will be always remain 0. That's why the line sortedList[m] = max; always inserts 9.2 to each index of your sorted array.
In such cases i recommend you to use an IDE of your choice(Intellij Idea, Eclipse, etc.) which will highlight compilation errors and help you to find your bugs using the integrated debugger.
So i just found your mistakes, i think now you can manage it. In case of additional help feel free to communicate.

Related

why is my second main method (bubble sorting?) not running?

the first part of my code is working fine, but the bubble sort part is not running at all, at least I don't believe it is, as I cannot get my code to print the sorted list. I have tried making everything doubles, and adding in to return the list, but I still cannot make it work
This is my code thus far:
public static void main(String[] args) {
// TODO Auto-generated method stub
//create array
double[] list = new double[10];
//Generates 10 Random Numbers in the range 1 -20
for(int i = 0; i < list.length; i++) {
list[i] = (int)(Math.random()* 100 + 1);
}//end for loop
System.out.println("The unsorted list is: " + Arrays.toString(list));
//find max number
double max = -1;
for (int i = 0; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
System.out.println("The largest value is " + max);
}
public static double[] bubbleSort(double[] list)
{
double temp;
for (int i = list.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
System.out.println("The sorted list is: " + bubbleSort(list) + " ");
}
}
}
return list;
}
}
In Java (and most languages), only the "Main" method runs automatically; that is the entry point for your code. Other methods won't run unless you call them.
You should look up "Control flow" to generally understand more of what gets run and when, but for now, you just need to call that method. Calling a method is what you're doing with code like Arrays.toString(list), but in this case the method is in the local namespace, so you just need bubbleSort(list)

How do I find the maximum number in an array in Java

I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:
double maximum = measurements[0];
for (i = 0; i < measurements.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also do this using Java stream api :
double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);
Or a more concise code:
double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);
Or, sort the array and return the last one
Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);
you can try this -
class MaxNumber
{
public static void main(String args[])
{
int[] a = new int[] { 10, 3, 50, 14, 7, 90};
int max = a[0];
for(int i = 1; i < a.length;i++)
{
if(a[i] > max)
{
max = a[i];
}
}
System.out.println("Given Array is:");
for(int i = 0; i < a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("Max Number is:" + max);
}
}
You have not declared i inside the for loop or before the for loop.
double maximum = measurements[0];
for (int i = 0; i < measurements.length; i++) { //You can declare i here.
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also declare i before the for loop also

for loops and snippets where we reassign variables

The task is: write a program that swaps the maximum and minimum elements of a given array. Print the array before and after this operation.
I am still a huge noob at programming, most of the time I just can't really picture what the codes are doing.
public class problem6 {
public static void main(String[] args) {
int[] arr = new int[15];
for (int i = 0; i < arr.length; i++)
/*
I don't think I really understand incrementation in loops, what exactly do they do? As far as I understand
it is like having an industry line? I suppose 'i' would be the product and '++' would be the thing that
carries 'i' to the be checked one by one? I really need an ape analogy because I can't really visualize it.
*/
arr[i] = (int) (Math.random() * 15);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
int minIndex = 0, maxIndex = 0; //why do we assign min and max to 0 and not any other number?
for (int i = 1; i < arr.length; i++) {
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
/*
I see a lot of codes like:
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
what purpose does it serve? For the lack of knowledge and from a really noob programmer's perspective
it seems like we are "reassigning" minIndex and maxIndex to 'i', which is probably not what we're actually doing
but I don't know how to describe it other way.
*/
}
System.out.println(minIndex + " " + arr[minIndex]);
System.out.println(maxIndex + " " + arr[maxIndex]);
{
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
/*
Here again, for the lack of understanding and better way of describing, it seems to me that we are reassigning,
which makes it appear illogical to me, but I'd assume it's not actually "reassigning".
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
*/
}
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
What is i, what does it do and what does i++ mean:
i is used in this loop to indicate how many times you've looped through said loop.
The ++ is there to do i + 1 after each time you've looped trough the for loop.
For better understanding on how you use i in your example, imagine the array arr being a big book and what you write in the [] is which page you want to open. In the loop you basically flip through the book to each pagenumber in those brackets.
Why does minIndex and maxIndex get set to 0 instead of any other number?
They get set to 0 because we can assume that that is the lowest possible Index in your array. So when the Index gets compared to any other possible number that could be the lowest or highest Index, it always gets set to said lowest or highest Index instead of always having the same value you set because no other value in your array is higher or lower than that.
Why do we make arr[minIndex] assert the same value as arr[maxIndex]?
In your question's title you said that you wanted to swap the highest number in your array with the lowest number. So now that we have found the highest and lowest number in your array these steps switch the two.
If you have any other questions or if any of my descriptions are unclear, just comment under the answer and I'll do my best to help you out. Also, don't look down on yourself so much. Everyone was a "noob" at some point :)
Here is quick fix for you.
Following is complete example of swaps the maximum and minimum elements of a given array.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
10
15
16
1
9
Output :
Element After swaps :
10
15
1
16
9
public static void main(String arg[]) {
Scanner scan = null;
int number;
try {
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
number = scan.nextInt();
int array[] = new int[number];
System.out.println("Enter all the elements:");
for (int i = 0; i < number; i++) {
array[i] = scan.nextInt();
}
int[] resultArray = swap(array);
System.out.println("Element After swaps :");
for (int i : resultArray) {
System.out.println(i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
scan.close();
}
}
public static int[] swap(int[] array) {
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i] < array[minIndex])
minIndex = i;
if (array[i] > array[maxIndex])
maxIndex = i;
}
int t;
if (maxIndex != minIndex) {
t = array[minIndex];
array[minIndex] = array[maxIndex];
array[maxIndex] = t;
}
return array;
}
Hope this solution works.
Please mark as answer if this solution is helpful.

How to find the most frequently repeated number from the command line, in an array?

I need to take single digit integers from the command line and put them into an array, and then find the most frequent integer. Sometimes this program seems to work, and other times, it doesn't.
public class MostFrequent {
public static void main(String[] args){
int num=0;
int[] freq= new int[9];//intialize array for integers 0-9
for (int i=0; i<args.length; i++){
try {
num = Integer.parseInt(args[i]);
freq[num]++;//adds to array counter
}
catch (NumberFormatException nfe) {
}
}
int max=0,j;
for (j=0; j<10; j++){
while(freq[j]>max){
max=freq[j];
}
}
System.out.println("The digit that appears most frequently is " + freq[j]);
}
}
Thanks everyone for your help, this is what ended up working for me, and thanks to whoever mentioned making the array more dynamic, that helped as well. Here is the code I finished with:
public class MostFrequent {
public static void main(String[] args){
int num=0;
int[] freq= new int[args.length];//intialize array for integers 0-9
for (int i=0; i<args.length; i++){
try {
num = Integer.parseInt(args[i]);
freq[num]++;//adds to array counter
}
catch (NumberFormatException nfe) {
}
}
int max=0,j;
for (j=1; j<args.length; j++){
while(freq[j]>freq[max]){//compares a max array val to the previous val
max=j;
}
}
System.out.println("The digit that appears most frequently is " + max);
}
}
The logic in your second loop is flawed. Also, you haven't allocated room for all digits in your array, you need an int[10] for this. One way to solve it is like this:
int[] freq = new int[10];//intialize array for integers 0-9
...
int maxindex = 0;
for (int j = 1; j < 10; j++){
if (freq[j] > freq[maxIndex]) {
maxIndex = j;
}
}
System.out.println("The digit that appears most frequently is " + j + ", that appears " + freq[j] + " times.";
Change your loop
int max=freq[0];
int maxIndex = 0;
for (j=1; j<10; j++){
if(freq[j]>max)
{
max=freq[j];
maxIndex = j;
}
}
Also, you have wrong output.
Instead of (that will give you last number)
System.out.println("The digit that appears most frequently is " + freq[j]);
Use (which prints max number and its number of occurence)
System.out.println("The digit that appears most frequently is " + maxIndex + " - " + max + "x");
Here is the implementation to find most frequent number.
#include<iostream>
using namespace std;
// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
int maxRepeating(int* arr, int n, int k)
{
// Iterate though input array, for every element
// arr[i], increment arr[arr[i]%k] by k
for (int i = 0; i< n; i++)
arr[arr[i]%k] += k;
// Find index of the maximum repeating element
int max = arr[0], result = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
result = i;
}
}
/* Uncomment this code to get the original array back
for (int i = 0; i< n; i++)
arr[i] = arr[i]%k; */
// Return index of the maximum element
return result;
}
// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 8;
cout << "The maximum repeating number is " <<
maxRepeating(arr, n, k) << endl;
return 0;
}

ArrayList IndexOutOfBoundsException while processing user input

I am trying to write a program that uses a sentinal contolled do-while loop, that repeatedly asks the user for positive integers.
The loop should end when a negative value is entered by the user. After the loop completes, your program should print out the minimum, maximum, average, and count of the positive numbers that
were entered by the user.
However when I run the program, I get the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at posNeg.main(posNeg.java:31)
I have searched for answers but none of them seem to be working. Most just suggest removing the = from the for (int i = 0; i <= (count); i++) {.
Anyway, here is the full code:
import java.util.*;
import java.lang.Math;
public class posNeg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList();
int num;
int count = 0;
do{
System.out.println("enter pos nums (or a neg num to quit): ");
num = sc.nextInt();
list.add(num);
count++;
} while (num >= 0);
Iterator it = list.iterator();
list.remove(list.get(count-1));
Object max = Collections.max(list);
Object min = Collections.min(list);
System.out.print(list);
int tot = 0;
for (int i = 0; i <= (count); i++) {
Object piece = list.get(i);
int piecenum = ((Number) piece).intValue();
tot = tot + piecenum;
}
double avg;
avg = tot/count;
System.out.println("the max is "+max+". the min is "+min+". the avg is "+avg);
}
}
When you build your list, you increment count.
So after building count==list.size().
After that you remove one item from the listbut don't change count.
So count==list.size()-1.
So your loop should be
for (int i = 0; i <= count-2; i++) {
because you have items from index 0 to count-2.
But instead of maintaining a count, you could simply do
for (int i = 0; i<list.size(); i++) {
Look at this loop:
for (int i = 0; i <= (count); i++) {
At this point the list only has count - 1 items, but you're looping count + 1 times. For the sake of sanity you should decrement count after the call to remove, and then also change the loop to the more idiomatic:
for (int i = 0; i < count; i++) {
Or, rather more simply:
for (Number number : list) {
...
}
This will only work after making list generic though:
List<Number> list = new ArrayList<Number>();
You should really be using generics for collections.
Better do it this way....
for (int i = 0; i < (count); i++) {
}
Or
Use the For-Each loop
for(Number n : list){
}
The bug is with count, as others have noted. I suggest using a conditional break; in your input loop to avoid adding the negative value to the list, and incrementing count. in the first place. You will still need to replace <= with < whenever using a language with zero based indexing.
try this list.size instead of count
for (int i = 0; i < list.size(); i++) {
Object piece = list.get(i);
int piecenum = ((Number) piece).intValue();
tot = tot + piecenum;
}
Some suggestions,,,
do{
System.out.println("enter pos nums (or a neg num to quit): ");
num = sc.nextInt();
if (num >= 0)
break;
list.add(num);
}while (true);
.. and for the next loop
int tot = 0;
for (int i : list ) {
//do your stuff
}
.. but you should really use a typed list
List<int> list = new ArrayList<int>()
... or something like that

Categories

Resources