Bubble sort output is incorrect - bubble-sort

This is my bubble sort code but I am confused why the output shows only 125.
int secondArray[] = {0, 1, 5, 2};
int num;
for (int i = 1; i < secondArray.length; i++) {
for (int j = 0; j < secondArray.length - i; j++) {
if (secondArray[j] > secondArray[j + 1]) {
num = secondArray[j];
secondArray[j] = secondArray[j + 1];
secondArray[j + 1] = num;
}
}
System.out.print(secondArray[i]);
}

It is because you are iterating from 1 -> int i = 1; but array starts from 0, so System.out.print(secondArray[i]); never have a chance to display first element.

Please run the below code:
int secondArray[] = {0, 1, 5, 2};
int num;
for (int i = 0; i < secondArray.length - 1; i++) {
for (int j = 0; j < secondArray.length - 1 - i; j++) {
if (secondArray[j] > secondArray[j + 1]) {
num = secondArray[j];
secondArray[j] = secondArray[j + 1];
secondArray[j + 1] = num;
}
}
}
for (int number : secondArray) {
System.out.print(number);
}

Check this out.
int secondArray[] = {0, 1, 5, 2};
int temp;
for (int i = 0, k = secondArray.length; i < secondArray.length / 2; i++) {
temp = secondArray[i];
secondArray[i] = secondArray[--k];
secondArray[k] = temp;
System.out.println(secondArray[0] + " " + secondArray[1]
+ " " + secondArray[2] + " " + secondArray[3]);
}

Bubble Sort - Java Code
import java.util.*;
class bubblesort {
public static void main(String[] args) {
int ar[] = {34, 12, 45, 3, 6, 7, 20};
sort(ar);
System.out.print("After sort : ");
for (int j = 0; j < ar.length; j++) {
System.out.print(ar[j] + " ");
}
}
public static void sort(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < (arr.length - 1 - i); j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}

Complete code of Bubble Sort:
class BubbleSort {
void bubbleSort(int array[]) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
void printArray(int array[]) {
for (int i = 0; i < array.length; ++i) {
System.out.print(array[i] + " ");
}
System.out.println();
}
// Main method
public static void main(String args[]) {
BubbleSort bubbleSort = new BubbleSort();
int array[] = {64, 34, 25, 12, 22, 11, 90};
System.out.print("Original array : ");
bubbleSort.printArray(array);
bubbleSort.bubbleSort(array);
System.out.print("Sorted array : ");
bubbleSort.printArray(array);
}
}
OUTPUT:
Original array : 64 34 25 12 22 11 90
Sorted array : 11 12 22 25 34 64 90

public class Example {
public static void sortArray(int[] x) {
for (int j = 0; j < x.length - 1; j++) {
for (int i = 0; i < x.length - 1; i++) {
if (x[i] > x[i + 1]) {
int temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] x = {32, 98, 35, 76, 26, 89, 1, 46, 21, 7};
System.out.println(Arrays.toString(x));
sortArray(x);
System.out.println(Arrays.toString(x));
}
}
Output:
[32, 98, 35, 76, 26, 89, 1, 46, 21, 7]
[1, 7, 21, 26, 32, 35, 46, 76, 89, 98]

Outer do-while-loop repeats the passes through the array until all the elements are in the correct order, and inner for-loop passes through the array and compares adjacent elements.
public static void bubbleSort(int[] arr) {
boolean swapped;
// repeat the passes through the array until
// all the elements are in the correct order
do {
swapped = false;
// pass through the array and
// compare adjacent elements
for (int i = 0; i < arr.length - 1; i++) {
// if this element is greater than
// the next one, then swap them
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
// if there are no swapped elements at the
// current pass, then this is the last pass
} while (swapped);
}
public static void main(String[] args) {
int[] arr = {6, 1, 5, 8, 4, 3, 9, 2, 0, 7};
System.out.println(Arrays.toString(arr));
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
Output:
[6, 1, 5, 8, 4, 3, 9, 2, 0, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
See also: Bubble sort with step-by-step output • Java 8

Related

Count number of elements that increase or decrease by a factor of 10 with recursion

#include <iostream>
using namespace std;
int factorsOf10(int arr[], int value)
{
int count = 0;
int len = sizeof(arr) / sizeof(0);
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
if (arr[i] * 10 = arr[j])
count++;
else
return(arr[] + 1, value);
}
}
}
int main()
{
int arr[] = { 1,10,20 };
int result = factorsOf10(arr, 0);
cout << result;
return 0;
}
This is what I have done so far but it went wrong. Can anybody give me some idea, please?
I need to compute recursively the number of consecutive elements that increase or decrease by a factor of 10.
For example:
factorsOf10([1, 10, 20], 0) → 1
factorsOf10([100, 10, 20, 200], 0) → 2
factorsOf10([1000, 100, 10, 1, 10], 0) → 4
factorsOf10([10, 20, 33, 340], 0) → 0

Getting vector subscript out of range exception

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> arr = { -12, 14, 71, 123, 12, -14, 5, 5, -75, 12, -1, 51, 12, 61, -61, -13 };
int n = arr.size();
for (int i = 0; i < n; i++)
{
for (int j=0;j<n;j++)
{
if (arr[j] < arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
else if (arr[j] == arr[j + 1])
{
for (int a = j + 1; a < n; a++)
{
arr[a] = arr[a + 1];
}
}
}
}
for (int i : arr)
{
cout << i << endl;
}
return 0;
}
It works if I use an array but it shown "vector subscript out of range" when I use vector. Could anyone please explain why is it an error there?
Consider the following fragment of your code:
for (int j=0;j<n;j++)
{
if (arr[j] < arr[j + 1])
What will happen on the last loop iteration, when j = n - 1?
You are trying to access out-of-bound array with this line:
arr[j + 1] AND arr[a + 1]
because it is iterating only till n. In the last valid iteration, the program tries to obtain the value of j + 1th and n + 1th indices respectively whereas the size of the array is n.
To solve this issue, you need to iterate till n - 1 condition. Just replace those n contained in the nested two For loops so that it will correctly iterate till the end of the loop.
your vector element size is n. But,you are using index over n incase of arr[j+1] and arr[a+1].
Just put condition checking, i < n-1 , j < n-1 and a < n-1
Here is the updated code:
vector <int> arr = { -12, 14, 71, 123, 12, -14, 5, 5, -75, 12, -1, 51, 12, 61, -61, -13 };
int n = arr.size();
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;
}
else if ( arr[j] == arr[j + 1])
{
for (int a = j + 1; a < n - 1; a++)
{
arr[a] = arr[a + 1];
}
}
}
}
for (int i : arr)
{
cout << i << endl;
}

Interleaved insertion sort function doesn't sort correctly

I have this function that is supposed to use insertion sort interleaving to prepare an array for shell sorting. I was testing the insertionSortInterleaved() function as stated below:
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
int i = 0;
int j = 0;
int temp = 0;
for (i = i + gap; i < numbersSize; i += gap) {
j = i;
while (j - gap >= startIndex && numbers[j] < numbers[j - gap]) {
temp = numbers[j];
numbers[j] = numbers[j - gap];
numbers[j - gap] = temp;
j = j - gap;
}
}
}
Now, in the main, I made an array of the numbers 1-20, but in descending order, then I made it print out each element of the array. I then made the main insertionSort the array and return the array again after sorting.
int main() {
int numbers[] = { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < 20; i++) {
cout << numbers[i] << " ";
}
cout << endl;
insertionSortInterleaved(numbers, 20, 1, 5); //numbers being the array, 20 being the amount of numbers being sorted, 1 being the starting index, and 5 being the gap space)
for (int j = 0; j < 20; j++) {
cout << numbers[j] << " ";
}
cout << endl;
system("pause");
return 0;
}
It outputs the original array just fine, but after the "sorting," it outputs the array in the same order as the first time.
Before: 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
After: 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
After sorting, shouldn't the numbers be in ascending order? If so, what am I doing wrong? Any help is appreciated! Thanks!
In while (j - gap >= startIndex || numbers[j] < numbers[j - gap]) use || operator. index + gap can also lead to out-of-range error watch out. I changed i = 0 in the for loop for that matter.
void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < numbersSize; i += gap) {
j = i;
while (j - gap >= startIndex || numbers[j] < numbers[j - gap]) { // changed Here
temp = numbers[j];
numbers[j] = numbers[j - gap];
numbers[j - gap] = temp;
j = j - gap;
}
}
}
int main() {
int numbers[] = { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < 20; i++) {
cout << numbers[i] << " ";
}
cout << endl;
insertionSortInterleaved(numbers, 20, 1, 1); //numbers being the array, 20 being the amount of numbers being sorted, 1 being the starting index, and 1 being the gap space)
for (int j = 0; j < 20; j++) {
cout << numbers[j] << " ";
}
cout << endl;
system("pause");
return 0;
}

C++ Bubble Sorting

Hey i got this algorithm from my class called Bubble Sort. It uses two "for" one inside the other. But when i tried to do it with "while" it didnt work, aren't they equivalent ?
void bubbleSort(int v[], int n) { // void workingBubble(int v[], int n){
int fim = n - 1; // int i, fim;
int i = 0; // for(fim=n-1; fim>0; fim--){
int aux; // for(i=0; i<fim; i++){
while (fim > 0) { // if(v[i] > v[i+1]){
while (i < fim) { // int temp = v[i];
if (v[i] > v[i + 1]) { // v[i] = v[i+1];
aux = v[i]; // v[i+1] = temp;
v[i] = v[i + 1]; // }
v[i + 1] = aux; // }
} // }
i++; // }
} //
fim--; //
}}
I commented the one that worked next to the other so i could compare, i thought it was the same but with while instead of for
Array = {10, 2, 8, 11, 5, 3, 27, 1}
Array after bubble sort = {2, 8, 10, 5, 3, 11, 1, 27}
Reset i to 0 each time before the inner loop:
void bubbleSort(int v[], int n) {
int fim = n - 1;
int i;
int aux;
while (fim > 0) {
i = 0;
while (i < fim) {
if (v[i] > v[i + 1]) {
aux = v[i];
v[i] = v[i + 1];
v[i + 1] = aux;
}
i++;
}
fim--;
}
}

incorrect output of merge sort

I am trying to write a merge sort algorithm using template functions in c++. The output is close but not correct. When I give the function the array [7, 6, 4, 8, 1, 2, 3], it returns [1, 1, 2, 2, 3, 3, 8]. I specifically believe that the problem is in the merge function rather than the merge sort function. Any help would be much appreciated. Here is my code:
template <class T1>
void mergeSort(T1 array[], int lower, int upper)
{
if (lower < upper)
{
int middle = (lower + upper) / 2;
mergeSort(array, lower, middle);
mergeSort(array, middle + 1, upper);
merge(array, lower, middle, upper);
}
}
template <class T1>
void merge(T1 array1[], int lower, int middle, int upper)
{
int i = 0,
j = 0,
k = 0;
int size1 = middle - lower + 1;
int size2 = upper - middle;
T1* temp1 = new T1[size1];
T1* temp2 = new T1[size2];
for (int i = 0; i < size1; i++)
{
temp1[i] = array1[lower + i];
}
for (int j = 0; j < size2; j++)
{
temp2[j] = array1[middle + 1 + j];
}
while (i < size1 && j < size2)
{
if (temp1[i] < temp2[j])
{
array1[k] = temp1[i];
i++;
}
else
{
array1[k] = temp2[j];
j++;
}
k++;
}
if (i == size1)
{
while (j < size2)
{
array1[k] = temp2[j];
k++;
j++;
}
}
else
{
while (i < size1)
{
array1[k] = temp1[i];
k++;
i++;
}
}
}
int main(){
int a[] = { 7, 6, 4, 8, 1, 2, 3 };
mergeSort(a, 0, 6);
}
Output:
1 1 2 2 3 3 8
In your merge function you shouldn't initialize k to 0 because it will write the result of merge in the wrong place. Instead you should initialize k to lower. Because that is the start index of the part you are actually sorting.