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;
}
}
Related
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 have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
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.
public class Sort {
public static void main(String[] args) {
//fill the array with random numbers
int[] unsorted = new int[100];
for(int i = 0; i < 100; i++) {
unsorted[i] = (int) (Math.random() * 100);
}
System.out.println("Here are the unsorted numbers:");
for(int i = 0; i < 100; i++) {
System.out.print(unsorted[i] + " ");
}
System.out.println();
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = -1;
int hiIndex = -1;
for(int j = 0; j < 100; j++) {
if(unsorted[j] > hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = -1;
}
System.out.println("Here are the sorted numbers: ");
for(int i = 0; i < 100; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
}
}
So this is in descending order but I want to reverse it.
I tried changing the if(unsorted[j] > hi) {
to a if(unsorted[j] < hi) {
[edit:changed greater than to less than, both were same]
Okay, you want the numbers to be in ascending order. So for descending, you assume that compared number would be -1 and all other number must be grater than this -1, now instead of -1 use the maximum value a number could be. Assign Integer.MAX_VALUE where you were assigning -1. So change your code like this:
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = Integer.MAX_VALUE;
int hiIndex = i;
for(int j = 0; j < 100; j++) {
if(unsorted[j] < hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = Integer.MAX_VALUE;