Using a counter in bubble sort - java

The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?
public static int sort(int arr[]) {
int length = arr.length;
int temp;
int count = 0;
for (int i = 0; i < (length); i++) {
for (int j = 1; j < (length); j++) {
if (arr[j - 1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
count++;
}
}
}
return count;
}

Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.
Proper approach should be like below:
int yourCounter = 0;
for (int i = 0; i < length; i++)
for (int j = 1; j < length-i; j++)
if (arr[j - 1] > arr[j]) {
//swap code
//yourCounter++;
}
your counter should give you proper result then.

Related

Calculate total number of combinations of size k in array using recursion in Java?

I am attempting to write a recursive method that COUNTS the number of combinations of k size in an integer array.
I can easily do this for a known value k (e.g. 3) as so:
int[] arr = {1,2,3,4};
int count = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
for(int k = j+1; k < arr.length; k++) {
count++;
}
}
}
However, I would like to be able to do this without a known k. I have found methods online that print the combinations using recursion, such as this one:
https://www.techiedelight.com/find-distinct-combinations-of-given-length/, but none that count them.
Simple case of modifying the method linked.
public static int recur(int[] A, int i, int k)
{
int count = 0;
if (k == 0) {
count++;
}
for (int j = i; j < A.length; j++) {
count = count + recur(A, j + 1, k - 1);
}
return count;
}

Java Sort, default sort function working only

I'm sorry to bother, I just started trying to learn to code by my own.
I set myself a task to practice my basics. I'm supposed to generate random ints to populate an Array size 10, after that I have to sort it, look for the min, max and average value of all of the ints in the array and tell if the number 25 is in the array.
As you can see, the idea is to practice array manipulation and I'm not supposed to use built in functions.
So far I've written a method for assigning the random numbers to the array and another one to sort it (bubble sort, since is what I'm trying to learn).
Unfortunately I'm not able to sort the array by calling my sorting method (mySort) if I write the sorting algorithm myself.
If I use the built-in function for sorting inside my sorting method and then call it, it works perfectly. So I guess that means my algorithm is wrong.
I hope you guys could guide me and illuminate me as to what I'm doing wrong.
public static int randomNum;
public static void main(String args[]) {
generateRandomNumber(myArray);
mySort(myArray);
System.out.println(Arrays.toString(myArray));
}
private static int[] generateRandomNumber(int[] myArray) {
Random numberGenerator = new Random(Integer.MAX_VALUE);
for (int i = 0; i < myArray.length; i++) {
randomNum = numberGenerator.nextInt(100);
myArray[i] = randomNum;
}
return myArray;
}
private static void mySort(int[] myArray) {
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; i++) {
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
}
if I change to this:
private static void mySort(int[] myArray) {
Arrays.sort(myArray);
}
}
it works perfectly
There are several errors in your sorting code. The corrected version looks like this:
private static void mySort(int[] myArray) {
for (int i = 0; i < myArray.length; i++) { // Removed -1
for (int j = 1; j < myArray.length - i; j++) { // Removed -1, corrected from i++ to j++
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
The -1 is not required since you use less than (<) in your loop condition. That means i or j will never exceed array size - 1.
Your code will work by making following changes to mySort function:
private static void mySort(int[] myArray) {
for (int i = 0; i <= myArray.length -1; i++) {// <= instead of <
for (int j = 1; j <= myArray.length- i -1; j++) {//j++ not i++ and do not miss =;
if (myArray[j] < myArray[j - 1]) {
int temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
}
}
}
}
In the inner loop, you are iterating over i instead of j. Fix it and it will work.
This is one of those annoying little pains in the ... code, which will haunt you
Start by taking a very, very close look at ....
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; i++) {
Can't see it? Look more closely at the second line...
for (int j = 1; j < myArray.length- i -1; i++) {
j is always 1 ... but why? Because you increment i in both loops 😱
If you change the to something more like...
for (int i = 0; i < myArray.length -1; i++) {
for (int j = 1; j < myArray.length- i -1; j++) {
you should find it fixes the issue

Implementing Bubble sort-two different ways or am I implementing different sorting algorithm altogether?

I was reading up on sorting algorithms, I finished selection and bubble sort and thought I should try to implement what I understood.It took me while to understand what I wrote intending to be selection sort(code snippet-1) wasn't implementing key features of selection sort at all(which is finding min of unsorted array and building sorted array one element at a time). So I wrote one more for selection sort(code snippet-3). But now, I'm curious about Snippet-1. Can someone tell me if it is bubble sort or not?
Code Snippet-1
public void sort(int[] arr) {
// code snippet-1
int n = arr.length;
for (int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(arr[i] > arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
Code Snippet-2
public void sort(int[] arr) {
// code snippet-2
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1; j++) {
if(arr[j] > arr[j+1]){
int temp=arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
Code Snippet-3
public void sort(int[] arr) {
// Code snippet-3
int n = arr.length;
for (int i = 0; i < n; i++) {
int min = i;
for(int j = i + 1; j < n; j++){
if(arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
Also, on a not so related account, can someone explain how the outer for loop condition (i.e i<n and i<n-1) doesn't affect the result in these cases? I only changed snippet-2's condition to j<n-1 as it gave me Arrayoutofbound error because of arr[j+1] term. Yes, I saw the entire thing in debug mode and animations too but still not completely clear how to choose a condition. I know I'm missing something here.
You have different approaches to bubble sort and the Arrayoutofbound exception is because of the comparison of n+1 element which is not there in the array.
In code snippet 2, you could also avoid one more loop by doing:
for (int i = 0; i <= n-2; i++)

java | Return a reversed array by FOR loop

I am stuck with an exercise which tells me to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
But it is throwing out three exact same numbers.
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:
public int[] reverse(int[] nums) {
int len = nums.length;
int[] result = new int[len];
for (int i = 0; i < len; ++i) {
result[len - i - 1] = nums[i];
}
}
From a first look, your code should be more like this:
public int[] reverse3(int[] nums)
{
// initialize a second array with the same length
int[] nums2 = new int[nums.length];
// initialize the nums2 index
int index = 0;
// you only need one loop for this (since we'll be incrementing the index of nums2)
for (int i = nums.length - 1; i >= 0; i--) {
nums2[index] = nums[i];
index++;
}
return nums2;
}
Swap the symetric values in the array like this :
public static void reverse(int[] nums) {
for (int i = 0; i < nums.length / 2; i++) {
int temp = nums[i];
nums[i] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = temp;
}
To reverse an array you only have to swap the elements until the midpoint:
public int[] reverse(int[] nums) {
int numsLength = nums.length;
for (int i = 0; i < numsLength / 2; i++) {
int temp = nums[i];
nums[i] = nums[numsLength - i - 1];
nums[numsLength - i - 1] = temp;
}
return nums;
}
This way is much more optimized.
Source: How do I reverse an int array in Java?
I am new to Java development and sorry if this question will be too
silly, but it seems like I am stuck with the exercise which tells me
to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
} } return nums2; }
But it is throwing out three exact same numbers. Could I please count
on some help? Thank you
Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:
int j = 0;
for(int i = nums.length -1; i >= 0; i--){
nums2[j] = nums[i];
j++;
}
But if you want to use only one array, you can do this:
for (int i = 0; i < nums.length/2; i++) {
int aux = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = aux;
}
There are so many efficient ways to do it but to make you understand i am gonna modify your own code
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = (nums.length-1) - i; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
int length = nums.length;
for (int i = length - 1; i >= 0; i--) {
for (int j = (length-1) - i; j < length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..

Move left if there is a zero

I am trying to create a program that will take an array of integers, say {2,0,32,0,0,8} that can be of any length, and make it so all of the nonzero numbers are to the left at the lower indexes, and all the zeros are moved to the end.
For example, {2,0,32,0,0,8} becomes {2,32,8,0,0,0}.
This array can be of any length and contain any nonnegative integers.
This is what I have so far:
public static int[] moveLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
However, when I do this, it doesn't work for the first and second characters. If I have {1,2,0,1} it will return {2,1,1,0} when it should return {1,2,1,0}. Any help?
Your inner loop should stop before index i. Change this
for (int j = 0; j < a.length; j++) {
to
for (int j = 0; j < i; j++) {
And then your code works for me.

Categories