I had an assignment for a class where I had to develop a simple number sort program.
My main is supposed to receive the user input and my sort class is supposed to interrupt and spit out the resulting numbers in ascending and descending order. The problem is that my main is taking the input but it's not putting it in order at all and I'm unsure why.
package main;
import sort.Sort;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int arr[] = new int[5];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<5; i++) {
System.out.print("Enter a number: ");
myScanner.nextLine();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
}
package sort;
public class Sort {
public void ascendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void descendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
I know I'm missing something in my Main, because I'm fairly certain I don't need to put anything else into the sort class.
You're code is perfect. You just missed one assignment in your main method.
Instead of myScanner.nextLine(); you should have written arr[i] = myScanner.nextLine();
myScanner.nextLine(); is getting the next line you enter in the console but it isn't saving it anywhere. arr[i] = myScanner.nextLine(); will save the value of the console in the arr array.
Everything else should work after that.
First you are getting user input using myScanner.nextLine() but not storing it. myScanner.nextLine() won't save anything which user enters .
Thus you need to store it in an array and then use it later. So your main method after the changes should be like this.
public static void main(String[] args) {
int arr[] = new int[3];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<3; i++) {
System.out.print("Enter a number: ");
arr[i] = myScanner.nextInt();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
And your sorting functions are also wrong. There you do some mis-calculations and return / log nothing. Thus you will not see anything in the console if you are not logging or returning anything.
public void descendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
public void ascendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
I hope this functions will work for your use case of ascending and descending sort.
Related
public class first {
public static void main(String args[]){
int arr[]={5,4,1,3,2};
for(int i=0; i<arr.length-1;i++){
int smallest=arr[i];
for(int j=i+1; j<arr.length;j++){
if(smallest>arr[j]){
smallest=arr[j];
}
}
//swap
int temp=smallest;
smallest=arr[i];
arr[i]=temp;
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
i have done this problem by getting the smallest in terms of index number
and the program works properly .
but when i am taking smallest in terms of number present at index number ,
this program did not work.your text
you need to save the smallest number index not the number it self so you know the positions to make the swap
for (int i = 0; i < arr.length - 1; i++) {
int indexOfSmallestNum = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[indexOfSmallestNum] > arr[j]) indexOfSmallestNum = j;
}
int temp = arr[i];
arr[i] = arr[indexOfSmallestNum];
arr[indexOfSmallestNum] = temp;
}
Write a bubble sort program that prints the number of swaps made after M number of iterations (In this case, ‘M’ should be an input value).
For example, if M = 0, the bubble sort program will perform 0 swaps in 0 iterations.
In bubble sort, an iteration is defined as the total number of times the outer loop runs. Assume that:
M <= the array size and
the program sorts in descending order.
The code should ask the user to input the values for M, the array size, and finally the elements of the array. So, there will be three types of inputs —
Input 1: The value of M
Input 2: The size of the array
Input 3: The elements inside the array
Sample Input:
2
4
1
2
3
4
Sample Output:
5
Please help me in solving the Bubble Sort Problem. Here I run the program but I am getting 3 in place of 5.
here's my code :
package com.company;
import java.util.*;
class Source {
static int totalBubbleSortSwaps(int[] array, int M) {
int pass=0;
boolean isDone;
for (int k = 0; k < ( array.length-1 ); k++) {
isDone=true;
for (int j = 0; j < array.length-k-1; j++) {
if (array[j] < array[j+1])
{
//isDone=false;
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
pass++;
}
}
if(isDone){
break;
}
}
//for (pass =1; pass <m; ++pass){
//for (k = 0; k < size; k++)
return pass;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
count the number of swaps made after M runs of the outer loop.
A couple observations.
you are sorting the values in descending order. Is that correct?
you need to only count the swaps while m > 0.
after each outer loop, decrement m by 1 (for each iteration of the outer loop).
you are not setting your isDone flag.
Here is what I came up with. I changed pass to swaps.
public class BubbleSort {
static int totalBubbleSortSwaps(int[] array, int m) {
int swaps = 0;
boolean isDone;
for (int k = 0; k < (array.length - 1); k++) {
isDone = true;
for (int j = 0; j < array.length - k - 1; j++) {
if (array[j] > array[j + 1]) { // <----- changed to > from <
isDone=false;
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
if (m > 0) {
swaps++; // <---- update swap count
}
}
}
if (isDone) {
break;
}
m--; <---- decrement m
}
return swaps;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
}
import java.util.Scanner;
class Source {
static int totalBubbleSortSwaps(int[] array, int m) {
int swaps = 0;
for (int k = 0; k < m; k++) {
for (int j = 0; j < array.length - k - 1; j++) {
if (array[j] < array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swaps++;
}
}
}
return swaps;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
The below code will give you the number of swaps done in bubble sort (descending order) when "M" iterations are done in the outer loop:
import java.util.*;
public class BubbleSortSwaps {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int M = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, M));
}
}
static int totalBubbleSortSwaps(int[] array, int M) {
int size = array.length;
int totalSwaps = 0;
for (int i = 0; i < M; i++) {
Boolean swap = false;
for (int j = 1; j < size - i; j++) {
int swapTemp = 0;
if (array[j - 1] < array[j]) {
swapTemp = array[j - 1];
array[j - 1] = array[j];
array[j] = swapTemp;
swap = true;
totalSwaps++;
}
}
if (!swap)
break;
}
return totalSwaps;
}
}
My program isn't sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:
import java.util.Scanner;
public class maxSorttt {
public static void main(String[] args) {
double[] ten = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < ten.length; i++)
ten[i] = input.nextDouble();
sort(ten);
}
public static void sort(double[] array) {
for (int i = array.length - 1; i < 0; i--) {
double currentMax = array[i];
int currentMaxIndex = i;
for (int x = i - 1; x < -1; x--) {
if (currentMax < array[x]) {
currentMax = array[x];
currentMaxIndex = x;
}
}
if (currentMaxIndex != i) {
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
I believe your problem is here:
for(int i=array.length-1; i<0; i--)
array.length is not less than 0 so the for loop never runs. You probably wanted
for(int i=array.length-1; i>=0; i--)
Be Simple!
public static void selectionSort(double[] arr) {
for (int i = 0; i + 1 < arr.length; i++) {
int minIndex = findMinIndex(arr, i + 1);
if (Double.compare(arr[i], arr[minIndex]) > 0)
swap(arr, i, minIndex);
}
}
private static int findMinIndex(double[] arr, int i) {
int minIndex = i;
for (; i < arr.length; i++)
if (Double.compare(arr[i], arr[minIndex]) < 0)
minIndex = i;
return minIndex;
}
private static void swap(double[] arr, int i, int j) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
I was writing the code for the least occurring element in the array and for some reason my logic goes wrong and the compiler just prints either the first or the second element in the array? anyone know what's wrong?
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
count = 0;
}
}
System.out.print(store);
}
}
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
static int leastFrequent(int arr[], int n)
// n is length of array
{
// Sort the array
Arrays.sort(arr);
// find the min frequency using
// linear traversal
int min_count = n+1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count < min_count) {
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
I guess you are trying to implement the following logic
Find the count of each element in the array
If you find an element with lower count - store the element
Repeat for each element in the array - to find the lowest element.
You should have rest the count at the end of the inner loop as,
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
}
count = 0;
}
System.out.print(store);
}
}
You have a single counter, so you'll lose this counting once you transition from one element to another.
You could hold an auxiliary map of counters and update it as you go, but frankly, using Java's streams will save you a lot of boilerplate code:
int leastOccuring =
Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())
.entrySet()
.stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::geyKey)
.get();
This would be the correct code for your program.
import java.util.*;
public class LeastOccuringElementInArray {
public static void main(String[] args) {
int m = 0;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++)
{
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++)
{ c = a[i] ;
for(int j =0; j <n ; j++)
{
if(a[j] == c)
{
count++ ;
}
if(j == (n-1))
{
if(m!=0 && m > count)
{
store = a[i];
m = count;
}
else {
m = count;
}
}
}
count = 0;
}
System.out.print(store);
scan.close();
}
}
I have tried the other questions like this but none seem to match it. I want it to repeat if the user enters Y after the numbers are sorted in the console.
Here is the code:
package compsorter;
import java.util.Scanner;
public class Ascending_Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("In Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
s.close();
}
}
Thanks!
Like this,
do{
//code here
//take input from user 'Y' or 'N'
}while(condition);
try do while for this reason.here is example of that : link
You can put
do { after
Scanner s = new Scanner(System.in);
and
} while(s.readLine().equals("Y"))
before
s.close();
You can do it with while loop.
Below is main method program you should have.
public static void main(String[] args) {
String flag = "Y";
Scanner s = new Scanner(System.in);
while (true) {
if ("Y".equalsIgnoreCase(flag)) {
int n, temp;
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("In Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
System.out.println();
System.out.print("Do you want to continue Y/N?");
flag = s.next();
} else {
break;
}
}
s.close();
}