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;
}
Related
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;
}
}
I want to implement a selection alignment that receives 10 integers and organizes them in ascending order.
However, when my code is operated, other things work normally, but only the first integer is not aligned.
Please let me know how to fix the code.
public static void sort(int[] array) {
Scanner sc = new Scanner(System.in);
System.out.println("put the int");
for (int i =0;i <array.length;i++) {
System.out.print((i+1)+": ");
int n = sc.nextInt();
array[i] = n;
for (int j = 1; j < array.length;j++) {
if (array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}
}
public static void main(String[] args) {
int[] my_array = {0,0,0,0,0,0,0,0,0,0};
sort(my_array);
}
}
You should set
int j = 0
in the inner for
If you want to implement Selctionsort
initialize the inner for with int j = i+1
change numbers if array[i] is greater than array[j] not the other way around
for (int i =0;i <array.length;i++) {
int minValue = array[i];
for (int j = i +1; j < array.length;j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}
You need to read the entire array in first, then you can sort it. Also, I don't consider your algorithm a true selection sort. In selection sort, you must find the minimum in the array of unsorted data. Then you swap. Your algorithm doesn't do that exactly.
To illustrate, I have broken the code into functions.
// Find the minimum value in the array, starting the search at "start"
// Returns the index of the minimum
static int findMinIndex(int[] array, int start)
{
int min = array[start];
int minIndex = start;
for (int i = start + 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
minIndex = i;
}
}
return minIndex;
}
// Swap 2 elements of an array
static void swap(int[] array, int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Selection sort the array, ascending
static void selectionSort(int[] array)
{
for (int i = 0; i < array.length; i++) {
// First find the minimum from i to the end of the array...
int minIndex = findMinIndex(array, i);
// ...then swap
if (minIndex != i) {
swap(array, i, minIndex);
}
}
}
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 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.
I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}