I want the user input in descending order. Output in ascending order is correct but in descending order its not working.
public static void main(String[] argu){
int[] i = new int[10];
Scanner sc = new Scanner(System.in);
for (int j = 0; j<=9 ; j++) {
i[j] = Integer.parseInt(sc.nextLine());
}
Arrays.sort(i);
System.out.println(Arrays.toString(i));
Comparator comparator = Collections.reverseOrder();
Arrays.sort(i,Collections.reverseOrder());
System.out.println(Arrays.toString(i));
Your line Arrays.sort(i,Collections.reverseOrder()); won't compile because an array ist not a collection. Use a List instead of an array and use it like this:
public static void main(String[] argu) {
List<Integer> i = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for (int j = 0; j <= 9; j++) {
i.add(Integer.valueOf(sc.nextLine()));
}
System.out.println("Sorted:");
Collections.sort(i);
i.forEach(System.out::println);
System.out.println("\nReversed:");
Collections.sort(i, Collections.reverseOrder());
i.forEach(System.out::println);
}
Or with streams:
i = Arrays.stream(i).boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue)
.toArray()
You could try to use Integer[] instead of int[]
Arrays.sort(i, Collections.reverseOrder()) doesnt work with primitives. If you need to sort using the above, try to read the values as Integer not int.
If you need to use primitives, use a simple comparator and pass it into the Arrays.sort() or use something like below:
Collections.sort(i, (int a, int b) -> return (b-a));
Try this:
//Sort the array in descending order
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
Related
I am a newbie here. I wanted to print out the duplicate elements in an array.
This code will print out the duplicate elements.
Suppose I'm taking an array of size 5 with elements [1,2,5,5,5]
This code will print:
Duplicate elements: 5,5,5 //(since 5 is being repeated thrice.)
But I want the output something like this
Duplicate Elements: 5 //( instead of printing 5 thrice)
import java.util.*;
import java.util.Scanner;
public class duplicateArray{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x =sc.nextInt();
int arr[]=new int[x];
int i,count=0;
for(i=0;i<x;i++){
arr[i]=sc.nextInt();
}
System.out.print("Array: ");
for(i=0;i<x;i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
System.out.print("Duplicate elements: ");
for(i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
System.out.print(arr[j]+" ");
}
}
}
}
}
The following code does it without creating any additional data structure. For each element, it counts the number of duplicates previously encountered and only prints the first duplicate.
If I were doing this in the real world, I would use a Set but I'm assuming you haven't learnt about them yet, so I'm only using the array that you've already created.
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}
One solution is to create a separate List to store any duplicates found.
That, in addition to using the .contains() method of the List, you can ensure only one entry per int is made.
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
Output:
Duplicates: [1, 5]
This is pretty simple however you need to sort array before. All you need to know if duplicate for an element exists or not and do the printing in the outside for loop. Rest is described in comments
Arrays.sort(arr); // Sort Array
for (int i = 0; i < arr.length; i++) {
boolean hasDuplicate = false; // Assume that arr[i] is not repeating
for (int j = i + 1; j < arr.length; j++) {
// Check if it is repeating
if (arr[i] == arr[j]) {
// If it repeats
hasDuplicate = true;
}
// Since array is sorted we know that there is no value of arr[i] after this
if (arr[i] != arr[j]) {
// Set i to the last occurrence of arr[i] value
i = j - 1;
break; // Since there no occurrence of arr[i] value there is no need to continue
}
}
// Print the element at i
if (hasDuplicate)
System.out.print(arr[i] + " ");
// In next iteration loop will start from the index next to the last occurrence of value of arr[i]
}
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}
Without using Hashmaps, I think your best option would be to first sort the array and then count the duplicates. Since the array is now in order you can print the duplicates after each number switch!
If this is for an assignment go ahead and google bubble sort and implement it as a method.
CONTEXT
I've been trying to fix this part of my program for a while now without much success. I essentially want to sort a String [] where each element is in the format: name:number (i.e. john:32).
PROGRESS
So far, my code splits each element and adds it to an equivalent int []. I then attempt to compare the elements in the int [] with selection sort and swap the elements in the String [].
PROBLEM
I'm getting java.lang.ArrayIndexOutOfBoundsException for my String [], which is called scores. Why is this?
scores = sort(scores); //ArrayIndexOutOfBoundsException here
public static String [] sort(String [] A) {
//equivalent array containing only integer part of score[i]
int[] tempArray = new int[A.length];
//populate tempArray
for(int i = 0; i < A.length; i++) {
//acquire numerical part of element
//ArrayIndexOutOfBoundsException here********
int num = Integer.parseInt(A[i].split(":")[1]);
//add to array
tempArray[i] = num;
}
/* Selection Sort: descendinG */
//compare elements (integer) in tempArray
for(int i = 0; i < tempArray.length; i++){
int index = i;
//search for integers larger for above index
for(int j = i+1; j < tempArray.length; j++ ){
if(tempArray[j] > tempArray[index]){
index = j;
}}
//swap elements in scores-array (String)
String temp = A[index];
A[index] = A[i];
A[i] = temp;
}
return A;
}
I agree with #shmosel
This can probably help you rooting out the bad apple
String scoreSplit[] = A[i].split(":");
if (scoreSplit.length() == 2){
int num = Integer.parseInt(A[i].split(":")[1]);
}
else{
system.out.println("Bad apple with "+ scoreSplit[0]); //some kind of logging
}
I have an ArrayList of LinkedLists (an array of linked lists). The LinkedLists contains integers (Integer).
private List<LinkedList> buckets;
buckets = new ArrayList<LinkedList>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
I later want to remove the items from the linked list (in the order they were added) and add them to an array list. When I try this:
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).removeLast());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
I get an error saying:
add(java.lang.Integer) in ArrayList cannot be applied to (java.lang.Object)
But when I cast it to an Integer (the commented out line), the array is full of null values. Anyone see what I am doing wrong?
Here is where I am adding items to bucket:
for (int i = 0; i < unsorted.size(); i++) {
int digit = (unsorted.get(i) / position) % 10;
buckets.get(digit).add(unsorted.get(i));
}
Note that sorted is an ArrayList<Integer>. When I trace it in debug mode, I can see that the LinkedLists have Integer objects with the correct values.
Screenshot of buckets contents:
Working Example:
class Ideone {
private static List<LinkedList<Integer>> buckets;
public static void main (String[] args) throws Exception {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(6);
arr.add(8);
arr.add(1);
arr.add(3);
arr.add(9);
System.out.println(arr);
arr = sort(arr);
System.out.println(arr);
}
public static ArrayList<Integer> sort(ArrayList<Integer> unsorted) {
buckets = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < unsorted.size(); i++) {
int digit = unsorted.get(i) % 10;
buckets.get(digit).add(unsorted.get(i));
}
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).poll());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
return sorted;
}
}
You are using the raw form of LinkedList here:
private List<LinkedList> buckets;
Because of this, removeLast will return Object, not Integer. Try
private List<LinkedList<Integer>> buckets;
and
buckets = new ArrayList<LinkedList<Integer>>();
Casting the return of removeLast to Integer was the pre-generics way of getting this to work. However, you never inserted any items into each LinkedList, so removeLast returns null. If you want something returned, first insert something into each LinkedList that gets inserted into buckets.
Casting to Integer would still work, but supplying Integer as the type argument to LinkedList is preferred, especially since you are using generics by supplying LinkedList as the type parameter to List already.
In your nested loop,
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
// ***** here *****
sorted.add(buckets.get(j).poll());
}
}
You look to be polling the wrong List.
Try changing
sorted.add(buckets.get(j).poll());
to:
sorted.add(buckets.get(i).poll());
Perhaps a cleaner more intuitive way to code this would be something like:
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.poll());
}
}
Although this may not work if the innerList has multiple items. Why not instead remove items safely with an iterator?
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (Iterator<Integer> iterator = innerList.iterator(); iterator.hasNext();) {
sorted.add(iterator.next());
iterator.remove(); // this guy is optional
}
}
Either that or simply use get(j)
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.get(j));
}
}
Although this isn't efficient use of a LinkedList
The item that you inserted into the ArrayList "sorted" is the item you took from the link list LinkedList.
But you never actually add any item to it. You simply just created a LinkedList and added it to your bucket list.
You need to add something into the temp list.
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
// Add something to the temp LinkedList
buckets.add(temp);
}
I am very new to java and I need to create an array that stores numbers and then outputs the numbers in sorted list the mean mode and median.
can anyone tell me if I am on the right track so far with the code below
int number=0;
ArrayList<Integer> listOfNumbers = new ArrayList<>();
Scanner scannerStream = new Scanner (System.in);
System.out.println("Enter list of numbers to Sort: (OR * TO END LIST)");
while(!(listOfNumbers = br.readLine()).equals("*"))
{
listOfNumbers = scannerStream.nextInt();
NumberList = listOfNumbers();
public Vector listOfNumbersSort (int number) {
for (int i=0; i<NumberList; i++) {
int Sort = listOfNumbers();;
return Sort;
// returns the mean
public Vector<Integer> listOfNumbersMean (int number){
return mean;
} // end
// returns the mode
public Vector<Integer> listOfNumbersMode (int number){
return mode;
} // end
// returns the median
public Vector<Integer> listOfNumberMedian (int number){
return median;
} // end
Thanks in advance for any help for advice provided
Use Collections.sort() to sort an ArrayList.
Use Arrays.sort() to sort an array.
can anyone tell me if I am on the right track so far with the code below
Your method definitions does not look good. You are passing a number and expecting the sortedlistofnumbers. Offcourse, if you already have a list, and you sorted it, and then if you get a new number and need to re-sort, then you can have the method signature as you have written, but not at the primary level.
The way you are accepting the list of number is not right. You need a loop. And when you use Arrays, since Arrays are fixed length, you should specify the size too.
see the below code for reference.
If you want to implement sorting in your way, there are various alogorithms like bubble sort.
Sorting Arrays
public class Sorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
int numbers[] = new int[count];
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("List before sorting..");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
Arrays.sort(numbers);
System.out.println("Sorted list");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
}
}
Sorting ArrayList
public class SorterList {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers.add(scanner.nextInt());
}
System.out.println("List before sorting..");
System.out.println(numbers);
Collections.sort(numbers);
System.out.println("Sorted list");
System.out.println(numbers);
}
}
Edit:
If you want to do custom sorting - say bubble sort algorithm,
int temp;
for (int i = 0; i < (count - 1); i++) {
for (int j = 0; j < count - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) // '> for ascending order'
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
class arrayDemo {
static void sort2D(int[][] B) {
boolean swap = true;
int oy=0;
int temp=0;
for(int ox=0;ox<B.length;ox++){
while(oy<B[ox].length) {
while(swap) {
swap = false;
for(int ix=0;ix<B.length;ix++) {
for(int iy=0;iy<B[ix].length;iy++) {
if(B[ox][oy]<B[ix][iy]) {
temp = B[ix][iy];
B[ix][iy] = B[ox][oy];
B[ox][oy] = temp;
swap = true;
}
}
}
}
oy++;
}
}
for(int row=0;row<B.length;row++)
for(int col=0;col<B[row].length;col++)
System.out.println(B[row][col]);
}
public static void main(String...S) {
int y[][] = {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
sort2D(y);
}
}
I am trying to sort a 2D array in ascending order.
Input: {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
Output: 30,20,10,10,9,8,8,7,5,3,0,2,3
Can someone help me know what is wrong with my code.
You are comparing elements that are not in the same row or column. Each sub-array should be sorted individually. You might want to reconsider this line if (B[ox][oy] < B[ix][iy]).
That code has a number of problems.
It throws ArrayIndexOutOfBoundsException. This is because all for loop tests test against B.length, which is not correct for inner arrays.
You are comparing every pair of elements, but some pairs are the reverse of other pairs, and the reverse pairs should not be tested. You need to limit the scope of your inner set of for loops, by starting at a different index.
To fix all these problems, the path of least resistance is to dump the 2D array into a 1D array and sort that, which is much easier.
Here is code that has been tested and shown to work:
static void sort2D(int[][] B) {
int count = 0;
for (int[] is : B)
for (int i : is)
count++;
int[] A = new int[count];
count = 0;
for (int[] is : B)
for (int i : is)
A[count++] = i;
int temp;
for (int i = 0; i < A.length; i++)
for (int j = i + 1; j < A.length; j++)
if (A[i] > A[j]) {
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + ",");
}