I created a program that does a Selection Sort function of array using the elements our input that is given by the user. I am struggling in creating a loop or method to call or show each iteration that is completed to reach the final output of the sorting. I am all open for suggestions. Thanks!
Here's the code :
private static String arrayToString(int[] a)
{
String str="[";
if(a.length>0)
{
str+=a[0];
for(int i=1; i<a.length; i++)
str+="|"+a[i];
}
return str+"]";
}
public static void sort(int[] a)
// Sort the contents of array a in ascending numerical order
{
for(int i=0; i<a.length-1; i++)
{
int pos = smallestPosFrom(i,a);
swap(a,i,pos);
}
}
private static int smallestPosFrom(int from,int[] a)
// Return the index of the smallest element in the section of
// array 'a' from that indexed 'from' to the end of the array
{
int pos=from;
for(int i=from+1; i<a.length; i++)
if(a[i]<a[pos])
pos=i;
return pos;
}
private static void swap(int[] a,int pos1, int pos2)
// Swap the elements indexed pos1 and pos2 within array a
{
int temp;
temp = a[pos1];
a[pos1] = a[pos2];
a[pos2] = temp;
}
And this is how I call them in my main :
System.out.println("The array you entered is:");
System.out.println(arrayToString(Array));
sort(Array);
System.out.println("After sorting, the array is:");
System.out.println(arrayToString(Array));
break;
I'm not sure that I understood you well, but if you would like to see how an array was changed after each iteration of sorting you can just add some print to System.out in 'sort' method:
public static void sort(int[] a)
// Sort the contents of array a in ascending numerical order
{
String arrayAfterIteration;
for (int i = 0; i < a.length - 1; i++)
{
int pos = smallestPosFrom(i, a);
swap(a, i, pos);
arrayAfterIteration = arrayToString(a);
System.out.println("The array after step N" + i + " is:" + arrayAfterIteration);
}
}
Related
I have the code for bubble sorting down below. I was wondering how I would be able to run more efficient and loop less amount of times
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
Any help would be greatly appreciated. I am new to coding and have been very stumped on how to improve efficiency and have it loop less times.
Bubble sort is an inefficiency sorting algorithm and there are much better sorting algorithm.
You can make a bubble sort more efficient, its called Optimized Bubble Sort (It is still quite inefficient)
Optimized bubble sort in short is, - you pass n times , but on the every iteration you 'bubble' the biggest (or smallest) element to the end of the array. Now that last item is sorted, so you don't have to compare it again.
I wrote this code last year, not to sure if it still works:
public static void bubbleSort_withFlag(Integer[] intArr) {
int lastComparison = intArr.length - 1;
for (int i = 1; i < intArr.length; i++) {
boolean isSorted = true;
int currentSwap = -1;
for (int j = 0; j < lastComparison; j++) {
if (intArr[j] < intArr[j + 1]) {
int tmp = intArr[j];
intArr[j] = intArr[j + 1];
intArr[j + 1] = tmp;
isSorted = false;
currentSwap = j;
}
}
if (isSorted) return;
lastComparison = currentSwap;
}
}
Here you can read on optimized bubble sort
Here you can find a list of different sorting algorithms that could be more efficient depending on your scenario.
This is the code from geeksforgeeks which generates and print bitstrings of n bits but I want to know instead of printing the array, how can I store the values of the array or return it so I can use the values in the main method.
import java.util.*;
class GFG
{
// Function to print the output
static void printTheArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
// Function to generate all binary strings
static void generateAllBinaryStrings(int n,
int arr[], int i)
{
if (i == n)
{
printTheArray(arr, n);
return;
}
// First assign "0" at ith position
// and try for all other permutations
// for remaining positions
arr[i] = 0;
generateAllBinaryStrings(n, arr, i + 1);
// And then assign "1" at ith position
// and try for all other permutations
// for remaining positions
arr[i] = 1;
generateAllBinaryStrings(n, arr, i + 1);
}
// Driver Code
public static void main(String args[])
{
int n = 4;
int[] arr = new int[n];
// Print all binary strings
generateAllBinaryStrings(n, arr, 0);
}
}
// This code is contributed by
// Surendra_Gangwar
Change the return type
Add a return statement
Like this:
// Function to generate all binary strings
static int[] generateAllBinaryStrings(int n,
// ^^^^^ change return type
int arr[], int i)
{
if (i == n)
{
printTheArray(arr, n);
return;
}
// First assign "0" at ith position
// and try for all other permutations
// for remaining positions
arr[i] = 0;
generateAllBinaryStrings(n, arr, i + 1);
// And then assign "1" at ith position
// and try for all other permutations
// for remaining positions
arr[i] = 1;
generateAllBinaryStrings(n, arr, i + 1);
return arr;
// ^^^^^^^^^^^ add return statement
}
So, why won't this code work it is returning the original list always (I haven't put the return statement, but can someone determine why the logic behind my selection sort algorithm is not working). Any help would be gladly appreciated!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayListDemo {
public static void main(String [] args) {
ArrayList <String> list = new ArrayList <String> (15);
list.add("Wilson");
list.add("Annans");
list.add("Manning");
list.add("Branday");
list.add("Smittens");
list.add(2, "Goddard Fey");
list.set((list.size()) - 1, "Brand Brandon");
list.add("Brand Boarders");
selectionSort(list);
}
static void selectionSort(ArrayList<String> a) {
int smallindex;
for(int i = 0; i < a.size(); i++) {
smallindex = i; // set first element as smallest
for(int j = i + 1; j < a.size(); j++) { // find smallest
if (a.get(j).compareTo(a.get(smallindex)) > 0) {
swap(a, i, j);
}
}
}
}
static void swap(ArrayList<String> a, int index1, int index2) {
String i_string = a.get(index1);
String j_string = a.get(index2);
String temp = i_string;
i_string = j_string;
j_string = temp;
}
}
Your swap(ArrayList<String> a, int index1, int index2) method creates local variables - i_string and j_string - and then swaps them. This has no impact on the contents of the input List a.
To change the value of the i'th element of the List a you must call a.set(i,newValue).
You can either implement the swap method yourself, or use the existing Collections.swap:
static void selectionSort(ArrayList<String> a) {
int smallindex;
for(int i = 0; i < a.size(); i++) {
smallindex = i; // set first element as smallest
for(int j = i + 1; j < a.size(); j++) { // find smallest
if (a.get(j).compareTo(a.get(smallindex)) > 0) {
Collections.swap(a, i, j);
}
}
}
}
If you wish to learn how to implement swap correctly, you can take a look at the JDK implementation:
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
As you can see, this method sets the value returned by l.set(j, l.get(i)) to be the new i'th element of the List. l.set(j, l.get(i)) sets the value l.get(i) as the new j'th element of the List and returns the previous j'th element. Therefore the new i'th element of the List becomes the previous j'th element.
I'm having some trouble sorting an array. I'm trying to sort it in ascending order.
My task is to get a series of integers from the user and store them into an array, then display them back to the user in ascending order. I was fine getting input from the user, storing it in the array and displaying them back. I was able to run my code and get the results I wanted but as far as getting the integers in the array in ascending order using selection sort, I was having a lot of difficulty with that.
The size of the array depends on the value that the user inputs, so it is set to the variable numValues rather than a number.
I get an error with the sort method I created. I'm getting syntax errors and void is an invalid type. I think I'm missing something and I'm not sure how to go about fixing this. If someone can point me in the right direction. Any help would be appreciated.
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("Here are the values you've entered, in ascending order");
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
} //End for
} // End method sort
keyboard.close(); // To close Scanner object
} //End method main
You cannot have another method inside main. Get the method sort(int[] values) out of main, and call it inside main.
You had another problem. Inside your sort method:
System.out.print(values[scan] + " ");
scan has to be replaced by n.
Here is the completed code:
import java.util.*;
public class Project {
public static void main(String[] args) {
int numValues; // The number of values user has
int [] values; // Array declaration for values
Scanner keyboard = new Scanner(System.in); // Scanner object to get input from user
System.out.println("How many values do you have?"); // To get number of values for array
numValues = keyboard.nextInt();
/*
* Array to hold number of values
*/
values = new int [numValues];
/*
* Loop to gather integer values
*/
for (int n=0; n < values.length; n++ )
{
System.out.print("Enter value " + (n+1) + ":" );
values[n] = keyboard.nextInt();
} //End for loop
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + " ");
}
System.out.println("Here are the values you've entered, in ascending order");
sort(values);
keyboard.close(); // To close Scanner object
}
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
} //End for
} // End method sort
} // End class Project
Your program will not executed or will not display correct result due to some reasons.
You are using "private static void sort(int[] values)" method in main method and it's not possible because we can't define method in another method. Either you have to create a separate method outside of main method or you can use sorting functionality in your main method also.
Another mistake is in below code. You are using scan variable for displaying result in ascending order. Here is should be n.
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
}
Your logic is correct. But it's little bit large for selection sort. Below is small way to do this.
public class SelectionSort
{
public static void main(String[]args)
{
int [] values = {15,14,13,12,11};
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("\nHere are the values you've entered, in ascending order");
sort(values);
}
private static void sort(int[] values)
{
int index = 0;
int index2 = 0;
int temp = 0;
for(index=0; index<values.length; index++)
{
for(index2 = index+1; index2< values.length; index2++)
{
if(values[index] > values[index2])
{
temp = values[index];
values[index]= values[index2];
values[index2] = temp;
}
}
}
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
}
}
}
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//the outer loop will switch the number
for(int i=0;i<arrayToSort.length;i++){
int indexSmal=i;
//the inner loop will search for the biggest number
for(int j=i+1;j<arrayToSort.length;j++){
//search for biggest number index starting from i index
if(arrayToSort[j]>arrayToSort[indexSmal]){
indexSmal=j;
}
}//end loop
//swap the number
int smallNum=arrayToSort[indexSmal];
arrayToSort[indexSmal]=arrayToSort[i];
arrayToSort[i]=smallNum;
}// end loop
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}
I have made a mergesort that is being juxtaposed with two already created selection and insertion sorts which both count the comparisons so that when executed the program illustrates which methods are faster.
I can't figure out how to get a count implemented into my mergeset
I really don't know if it's even working correctly or if I'm just displaying a previously already sorted array, that was sorted by selection or insertion above it. I think this because I wasn't able to call the method how the selection and insertion were. (You'll see below)
I'll post full code so far so you can see selection and insertion, how they were used.
Arraysort.java
public class ArraySort {
private long[] a; // ref to array a
private int nElems; // number of data items
public ArraySort(int max) // constructor
{
a = new long[max]; // create the array
nElems = 0; // no items yet
}
public void Clone(ArraySort c) // c is another array
{
c.nElems = this.nElems; // Copy nElems
System.arraycopy(this.a, 0, c.a, 0, this.nElems); // Copy elements
}
public void insert(long value) // put element into array
{
a[nElems++] = value; // insert value
}
public String toString() // displays array contents
{
String res="";
for(int j=0; j<nElems; j++) // for each element,
res = res + a[j] + " "; // append it to res
return res;
}
private int insertOrder(int n, long temp) { // insert temp into a[0..(n-1)]
// and keep a[0..n] sorted.
int count = 0;
while (n>0) {
count++; // count next comparison
if (a[n-1] > temp) { // until one is smaller,
a[n] = a[n-1]; // shift item to right
--n; // go left one position
} else break;
}
a[n] = temp; // insert marked item
return count;
}
public int insertionSort() {
int count = 0;
for (int n=1; n<nElems; n++)
count += insertOrder(n, a[n]); // insert a[n] into a[0..(n-1)]
return count;
} // end insertionSort()
private void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
public int selectionSort() {
int out, in, max, count=0;
for(out=nElems-1; out > 0; out--) { // outer loop
max = out; // max is maximum item's index
for(in=0; in<out; in++) { // inner loop
if(a[in] > a[max] ) // if max is smaller,
max = in; // we have a new max
count++; // count one comparison
}
swap(out, max); // swap them
} // end for(out)
return count;
} // end selectionSort()
public void mergeSort() {
long[] ws = new long[nElems];
recMergeSort(ws, 0, nElems-1);
}
public void recMergeSort(long[] ws, int lower, int upper) {
if (lower == upper)
return;
else {
int mid = (lower + upper) / 2; //find midpoint
recMergeSort(ws, lower, mid); //sort lower
recMergeSort(ws, mid+1, upper); //sort upper
merge(ws, lower, mid+1, upper); //merge
}
}
public void merge(long[] ws, int lowPtr, int highPtr, int upper) {
int j = 0;
int lower = lowPtr;
int mid = highPtr-1;
int n = upper-lower+1; //# of items
while(lowPtr <= mid && highPtr <= upper)
if( a[lowPtr] < a[highPtr] )
ws[j++] = (int) a[lowPtr++];
else
ws[j++] = (int) a[highPtr++];
while(lowPtr <= mid)
ws[j++] = (int) a[lowPtr++];
while(highPtr <= upper)
ws[j++] = (int) a[highPtr++];
for(j=0; j<n; j++)
a[lower+j] = ws[j];
}
public void display() {
for(int j=0; j<nElems; j++) {
System.out.print(a[j] + " "); }
System.out.println("");
}
//end
}
SortComparison.java
import java.util.*;
public class SortComparison {
public static void main(String[] args) {
int count, maxSize = 100; // array size
ArraySort arr, carr; // reference to array
arr = new ArraySort(maxSize); // create the arrays
carr = new ArraySort(maxSize);
// insert some random numbers
Random generator = new Random();
for (int i = 0; i < 20; i++) {
arr.insert(Math.abs(generator.nextInt())%maxSize);
}
System.out.println("Before sort: " + arr); // display items
arr.Clone(carr);
count = carr.insertionSort(); // insertion-sort a clone of arr
System.out.println("\nInsert sort: \n" + carr + " ### Comparisons: " + count);
arr.Clone(carr);
count = carr.selectionSort(); // selection-sort a clone of arr
System.out.println("\nSelect sort: \n" + carr + " ### Comparisons: " + count);
carr.mergeSort();
System.out.println("\nMerge sort: ");
carr.display();
}
}
You can see how things should be called, with the count returning, by selection and insertion..
There are several ways you could return the count in addition to the sorted array. You could store either the count or the array as class variables. You could create an object which encapsulates both the count and the array. You could even tack the count onto the front of the array, if you promise to remember that the first element is the count, not a part of the sort (this is probably a bad idea).
You might want to check that your sort works correctly by copying the array again before you worry about counting the number of comparisons.