I am trying to make a method for comparisons in my bubble sort class. However, I keep getting the same value. Is there any way to fix this? Thanks.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
count++;
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The inner loop index j is not used, and it has incorrect bounds.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = i; j < array.length - 1; j++)
{
count++;
if ((array[j] > array[j + 1])) //Swaps the elements
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The outer loop index i is the same value for all the values of j in the inner loop. Looks like the compare logic should be using the inner loop index j.
If count is supposed to record the number of swaps done during the sort, perhaps it needs to be in the block of code performing the swap. At the moment, count++ will always execute the same number of times.
Try this:
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
count++;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
You better try to increment value of count inside the if-condition. You can place count++ anywhere inside if-condition, based upon requirements.
Related
As follows, I want to reverse the array. But my code doesn't work. This is my for loop. Please take a look. Is this for loop right.Codes are below.
int[] array = new int[]{2,3,5,7,11,13,17,19};
System.out.println("Before reversal:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
for (int i = 0,j = array.length - i - 1; i < j; i++) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
System.out.println();
System.out.println("After reversal:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
This is what I would do:
for (int i = 0; i < array.length/2; i++) {
int temp = array[i];
array[i] = array[array.length-i-1];
array[array.length-i-1] = temp;
}
The conditional in the for-loop is integer division, meaning this will work with arrays of both even and odd lengths.
for (int i = 0,j = array.length - i - 1; i < j; i++) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
The value of j is never updated, and the initial value of j should be array.length-1 because i is just 0.
You have 3 options, the first changing the for statement:
for(int i=0, j=array.length-1; i<j; i++, j--) //YOUR CODE
The second would be changing the last assignment to array[j--] = temp;
And the third would be adding a j--; after the last assignemnt.
Any of them should solve your problem.
I have a selection sort implemented to sort an array of random integers. I would like the user to choose between ascending or descending order. The ascending sort works flawlessly, although descending does not. Here is what my selection sort looks like:
public String selection(int[] array,int num,String order) {
String output = "";
int min;
// This is the descending selection sort
if (order == "desc") {
for (int i = num - 1; i >= 0; i--) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
} // This is the ascending selection sort
else {
for (int i = 0; i < num; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
}
return(output.trim());
}
I've seen a few questions similar to mine, although none of the questions I saw had their selection sort set up like this so I was unable to implement their solutions.
Firstly, the if blocks should compare to minPosition and maxPosition, not i. Secondly, if you are selecting both minimum and maximum, then your inner for loop should stop at a.length - i, not a.length (since the top i elements are also sorted). Doing both gives you this as the ascending order algorithm.
public static void SortAscending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
To switch to descending order, simply add one line.
public static void SortDescending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,minPosition,maxPosition); // <-- this line
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
Use swap function https://www.geeksforgeeks.org/collections-swap-method-in-java-with-examples/
I need to switch from increasing to decreasing. Here is what I have:
public static void bubbleSort(double[] array) {
boolean swapping = true;
for (int i = 1; i < array.length && swapping; i++) {
// array is already sorted if no swapping happened in the previous inner loop
swapping = false; // assume no swapping, before entering the inner loop
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
double temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapping = true;
}
}
}
printArray(array);
}
I have one problem. I need to print time and steps of sorting. I did time but I do not how to print steps.
class BubbleSort {
public static void main(String[] args) {
int[] randomNums = new int[20];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (100 * Math.random());
}
System.out.println("Numbers before sorting: ");
for (int i = 0; i < randomNums.length; i++) {
System.out.print(randomNums[i]+" " );
}
System.out.println();
long time = System.nanoTime();
bubbleSort(randomNums);
long elapsed = System.nanoTime() - time;
System.out.println("\nBubble sort time is " + elapsed + " nanoseconds passed, " + elapsed / 1000000000 + " seconds passed");
}
static void bubbleSort(int[] arr) {
int numbers = arr.length;
int temp = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
}
For listing down steps we can simply use a sysout to do the thing. The crux here is to know how this sorting algo is actually doing the sorting part. The swapping part is the actual sort code.
int step = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
System.out.println("step #" + step + ". swapping " + arr[j - 1] + " and " + arr[j])
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
step++;
}
}
}
This feature is supposed to add an element at the selected index and push all other in the array elements down. So, for instance, say I have the following array:
[0] = zero
[1] = one
[2] = two
if I add another element at index 0 called NEWZERO, the array has to look like this:
[0] = NEWZERO
[1] = zero
[2] = one
[3] = two
but currently I'm getting IndexOutOfBounds exception and it doesn't work, although my array is much bigger than just 3 elements.
P.S. I don't want to use the built-in ArrayList library, which automatically does it for you.
public void insert(int i, String s) {
if (array[i] == null) {
array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
} else {
for (int j = i; j < array.length; j++) { //Can't use >= i
array[j + 1] = array[j]; //THIS IS WHERE I GET THE ERROR.
if (j == array.length - 1) {
break;
}
}
array[i] = s;
extendArray(); //If an element is inserted properly, the array becomes array.length + 1
I'm not getting the error because there's no space in my array. Even if I have an array with 20 elements, and I'm working with just 3, I still get the OutOfBounds error. Here's my extend array method for when a user runs out of array space.
public void extendArray() {
String[] items2 = new String[items.length + 1];
for (int j = 0; j < items.length; j++) {
items2[j] = items[j];
}
items = items2;
}
When you initializes an array, it exists from 0 to length-1 values.
in your code
for (int j = i; j < array.length; j++) { //Can't use >= i
array[j + 1] = array[j]; //THIS IS WHERE I GET THE ERROR.
you are trying to store values to array[length] that is out of the bounds of the array.
so change the for to
for (int j = i; j < array.length - 1; j++) { //Can't use >= i
array[j + 1] = array[j];
When j reaches array.length-1 in the loop, the array[j + 1] is out of bounds.
To fix this, change the stopping condition (and get rid of the break since it's completely unnecessary):
for (int j = i; j < array.length - 1; j++) {
array[j + 1] = array[j];
}
Finally, you might want to replace the entire loop with a single call to System.arraycopy().
You already have a condition for j in the loop, so why do you need to second one? Just use
for (int j = i; j < array.length - 1; j++) { //Can't use >= i
array[j + 1] = array[j];
}
try this fix
for (int j = i; j < array.length - 1; j++) { //Can't use >= i
array[j + 1] = array[j];
}
besides it makes sense to extend the size of the array before inserting the new element
When j wil reach at the end , j+1 will be out of bound and cause arrayIndexoutOfBoundException
Solution :
Change the for loop like below
for (int j = i; j < array.length - 1; j++) { //Can't use >= i
array[j + 1] = array[j];
}