Find the nth smallest number - java

Here is my code
import java.util.Scanner;
public class NthSmallest{
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size of the array");
final int N = 15;
int n = input.nextInt();
int array[] = new int [N];
System.out.println("enter 15 number ");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
System.out.println(findNthSmallest(array, n ));
}
public static int findNthSmallest( int array[], int n ){
int i, j,t=0;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(array[j-1] > array[j]){
t = array[j-1];
array[j-1]=array[j];
array[j]=t;
}
}
}
return array[n-1];
}
}
When I want to find fifthSmallestNumber and enter 5 as the first input, the program finds the number five not fifth smallest number. How can I fix it?

In your for loop, it should be :
for(i = 0; i < array.length; i++){
for(j = 1; j < (array.length-i); j++){

Try this:
public static int findNthSmallest(int[] array, int n) {
Arrays.sort(array);
return array[n-1];
}

Related

How many times a number occurs

I need to write a program that reads an array of ints and an integer number n. The program must check how many times n occurs in the array.
Input:
The first line contains the size of the input array.
The second line contains elements of the array separated by spaces.
The third line contains n.
Output:
The result is only a single non-negative integer number.
My code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
int n = scanner.nextInt();
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
Test input:
6
1 2 3 4 2 1
2
My result: 1
My question is why int n = scanner.nextInt();read "1". It should "2".
Reading the n variable was in the wrong place. The solution:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
int n = scanner.nextInt();
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
You should read n after you read the array like so:
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);

Array index out of bounds exception in java code

I am writing the code to print a matrix on taking user input in the form of n value:
Suppose if,
n= 3
output:
3 3 3
3 0 3
3 1 3
3 2 3
3 3 3
I am getting ArrayIndexOutOfBoundException in the line: a[i][j]=n;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done. TheArrayIndexOutOfBoundsException is aRuntime Exception thrown only at runtime.
Look at this line:
for(int j=0;i<n;j++)
you increment while "i < n" but you increment "j++".
When your j reaches value 3, the inner loop continues, but exceeds the array-length (of 3, because the hightest array-index is actually 2).
(Also on a minor sidenote, it is usually preferrable to write ++i or ++j within for-loop increments. This is not a rule, just easier to read for most oldscool c-Devs). Also consider leaving spaces to inprove readability:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][] = new int[n][n];
int b = 0;
int mid = n / 2 + 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + j == mid) {
a[i][j] = n - b;
b++;
} else {
a[i][j] = n;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
minor correction in a loop
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++) //minor correction here
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

How to swap the largest number with the last number in an array?

I'm trying to create a program that asks the user to input a number which is how many random numbers between 1-100 will be generated in an array. Then I want the largest number to be swapped with the last number and the smallest number to be swapped with the first number. Here is my code so far:
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
}
if (myArray[i] < smallest) {
smallest = myArray[i];
}
}
for (int j = 1; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
}
}
}
I can't seem to get the numbers to properly swap. I created a loop which determines the smallest and largest numbers from the ones generated and these are stored. Then I create a loop which performs the necessary swaps but I can't seem to get it to work properly. It works fine for swapping the largest number with the last number but most of the time(not always) the outputted last number is also present somewhere else in the array. Here is what I mean:
input: 10
output: 62 48 34 0 91 14 64 60 91
I know there is a swapper method that I could use but I want to do it by manually swapping the numbers. Any help is appreciated, thanks.
you have one simple mistake, your loop should start from '0' when you perform the swap
for (int j = 0; j < myArray.length; j++) {
int first = myArray[0];
myArray[0] = smallest;
smallest = first;
int temp = largest;
int last = myArray.length;
myArray[last - 1] = largest;
temp = myArray[last - 1];
System.out.print(myArray[j] + " ");
Instead of a loop do
//find and stores poition of small
int smallPos = myArray.indexOf(small);
//stores tge values at 0
int tempSmall = myArray[0];
//swaps the values
myArray[0] = small;
myArray[smallPos] = smallTemp;
Just repeat this with the largest value and print it using a for loop. Tell me if it works.
I just tried this. Hope this helps.
public class App {
static int[] a = new int[100];
public static void main(String[] args) {
int i;
for(i = 0; i<a.length;i++)
a[i] = (int)(java.lang.Math.random() * 100);
int smallest = 0, largest = 0;
for(i =1; i<a.length; i++){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0,smallest);
swap(a.length-1,largest);
for(i =0; i<a.length;i++)
System.out.print(a[i] + " ");
}
public static void swap(int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Your last loop doesn't do anything loopy. It just does the same thing over and over. And what it does is not correct. It is swapping the smallest into the first element but it's not moving the first element anywhere: it's gone.
You need to keep track of where the largest and smallest elements were. Your swap logic doesn't take that into consideration.
Write this code
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
int smallest = myArray[0];
int largest = myArray[0];
int pos1,pos2;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
pos1=i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
pos2=i;
}
}
myArray[pos1]=myArray[myArray.length-1];
myArray[myArray.length-1]=largest;
myArray[pos2]=myArray[0];
myArray[0]=smallest;
for (int j = 1; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
}
i would advise against using a scanner or random values for testing since the result cannot be reproduced (at least not in an easy way). Be careful with what is an arrays index and what is the value at a specific index. This can lead to confusion very quickly. ^^
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
private static int[] myArray;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
//int num = scan.nextInt(); //skip this for testing ^^-d
int num = 10;
myArray = new int[num];
for (int i = myArray.length-1; i > 0; i--) {
//int randomInt = randomGenerator.nextInt(100);
int randomInt = i; //use test condition that can be reproduced!
myArray[i] = myArray.length-i;
}
int smallest = 0;
int largest = 0;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largestIndex = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
smallestIndex = i;
}
}
switchIndexOfmyArray(0, smallestIndex);
switchIndexOfmyArray(myArray.length-1, largestIndex);
for (int j = 0; j < myArray.length; j++) {
System.out.print(myArray[j] + " ");
}
}
public static void switchIndexOfmyArray(int index, int switchWithIndex){
int temp = myArray[index];
myArray[index] = myArray[switchWithIndex];
myArray[switchWithIndex] = temp;
}
}
Yielding
0 1 8 7 6 5 4 3 2 9
I admit i was slow on this one since i am hungry and tired xD
Happy coding! ^^
You did well by finding smallest and largest. Issue was in swap. I refactor the swap method. May be it works.
import java.util.Scanner;
import java.util.Random;
public class smallbig
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = randomGenerator.nextInt(100);
myArray[i] = randomInt;
}
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println();
int smallest = myArray[0];
int largest = myArray[0];
int sIndx = 0;
int lIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
lIndx = i;
}
if (myArray[i] < smallest) {
smallest = myArray[i];
sIndx = i;
}
}
System.out.println();
System.out.println("Smallest = "+smallest);
System.out.println("largest = "+largest);
System.out.println("Smallest Index = "+sIndx);
System.out.println("largest Index = "+lIndx);
swapSmallAndLargest(num, myArray, sIndx, lIndx);
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
private static void swapSmallAndLargest(int num, int[] myArray, int sIndx, int lIndx) {
int temp = 0;
temp = myArray[sIndx];
myArray[sIndx] = myArray[0];
myArray[0] = temp;
temp = myArray[lIndx];
myArray[lIndx] = myArray[num-1];
myArray[num-1] = temp;
}
}

Sorting numbers with user input in an array Java

I'm a beginner at java and I have a hopefully simple question.
I can get the numbers in order, but only a certain amount of numbers are added to the array. When there is a number less than the smallest number, it replaces that smallest number (the previous smallest gets removed from array). What can I do so that all of the array spots can be filled in?
public class apples {
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num=IO.readInt();
double array[]=new double[num];
double temp;
boolean fixed=false;
while (fixed==false){
fixed=true;
for(int j=0; j<num;j++){
double x = IO.readDouble();
array[j] = x;
for (int i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
fixed=false;
}
}
}
System.out.println("Sorted list of integers:");
for (int i = 0; i < num; i++)
System.out.println(array[i]);
}
}
}
}
First read in the numbers, then sort the array (and it's an array of double not int). Something like,
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int j = 0; j < num; j++) {
System.out.printf("Please enter double %d:%n", j + 1);
array[j] = IO.readDouble();
}
System.out.println("unsorted array: " + Arrays.toString(array));
Arrays.sort(array); // <-- or however you want to sort the array.
System.out.println("sorted array: " + Arrays.toString(array));
}
public static void main(String[] args) {
System.out.print("How many numbers: ");
int num = IO.readInt();
double array[] = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("["+i+"]Please enter your double");
array[i] = IO.readDouble();
}
//Sort
double temp = 0;
for (int i = 0; i < num - 1; i++) {
for (int j = i + 1; j < num ; j++) {
if (array[j] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//Result
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr[]=new int [n];
for (int i =0;i<n;i++){
arr[i]=sc.nextInt();}
Arrays.sort(arr);
//if(n%2==0){median}
System.out.println( Arrays.toString(arr));
}
}

How to make Bubble Sort in Java to output the sorted numbers?

This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}

Categories

Resources