#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;
}
Related
This code is supposed to be an Insertion sort but is it implemented as such? I'm lost. The first loop goes through the array and checks if the next element is smaller than the current element. The nested loop inserts the next element(j) correctly in its place in the sorted portion of the array.
#include <iostream>
using namespace std;
// Print array
void printArray(int array[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
int main()
{
int array1[] ={5, 3, 1, 9, 8, 2, 4, 7};
int array1Size = sizeof(array1)/sizeof(int);
printArray(array1, array1Size);
for (int i = 0; i < array1Size - 1; i++)
{
int oldNum = array1[i];
if (array1[i] > array1[i + 1])
{
array1[i] = array1[i + 1];
array1[i + 1] = oldNum;
}
int newI = array1[i];
// Check if arranged correctly
if ( i > 0)
{
// Swap bigger number and newI
for (int j = i - 1; newI < array1[j]; j--)
{
if (j < 0)
{
break;
}
array1[j + 1] = array1[j];
array1[j] = newI;
}
}
printArray(array1, array1Size);
}
return 0;
}
The key to insertion sort is to maintain a "sorted zone" and expand it in loop. In the beginning the zone is only one element, and finally it's all the list. We take an element outside the sorted zone and decide which position in sorted zone that it should be placed in.
BTW, loop invariant is easy to understand but powerful and awesome. Recommended.
int main() {
int array1[] ={5, 3, 1, 9, 8, 2, 4, 7};
int array1Size = sizeof(array1)/sizeof(int);
// loop invariant: array1[0..i-1] is sorted
// array1[i] is the element to be inserted
for (size_t i = 1; i < array1Size; i++) {
int temp = array1[i];
// find the right place to insert array1[i]. Can be replaced by binary search(but moving elements is more expensive than comparing)
size_t j = i; // j is used to save the right place
for (; j > 0 && array1[j-1] > temp; j--) {
array1[j] = array1[j-1];
}
array1[j] = temp;
}
return 0;
}
This for loop
for (int j = i - 1; newI < array1[j]; j--)
{
if (j < 0)
{
break;
}
array1[j + 1] = array1[j];
array1[j] = newI;
}
can invoke undefined behavior when j is equal to -1 due to this expression in the condition of the for loop
newI < array1[j]
And the code is too complicated. For example this code snippet
if (array1[i] > array1[i + 1])
{
array1[i] = array1[i + 1];
array1[i + 1] = oldNum;
}
where two elements are swapped is redundant. And this if statement
if ( i > 0)
{
also is redundant. It is enough to start the outer loop from 1 instead of from 0.
It is better to define a separate function. It can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Pay attention to that the operator sizeof yields a value of the type size_t. You should use this type size_t for the variable that will be store the number of elements in the array. In general the type int is not large enough to store sizes of arrays.
If your compiler supports C++ 17 then instead of using the expression with the sizeof operator
int array1Size = sizeof(array1)/sizeof(int);
you could write at least
#include <iterator>
//...
int array1Size = std::size( array1 );
Also as the function printArray does not change the passed array then it first parameter should be declared with the qualifier const.
void printArray(const int array[], int arraySize);
Here is a demonstration program that shows usage of a separate function that sorts arrays using the insertion sort method..
#include <iostream>
#include <iterator>
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
int main()
{
int array1[] ={5, 3, 1, 9, 8, 2, 4, 7};
for ( const auto &item : array1 )
{
std::cout << item << ' ';
}
std::cout << '\n';
InsertionSort( array1, std::size( array1 ) );
for ( const auto &item : array1 )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
The program output is
5 3 1 9 8 2 4 7
1 2 3 4 5 7 8 9
I tried using for loop, but it gives a wrong answer. When I used a while loop in its place the sorting is done as expected. Can someone help me debug?
Note : It doesn't throw an compilation error, just gives a wrong ans when using for loop. And I have tried running on different IDE's and even tried dry running the for loop, but I am unable to understand the problem here.
//While loop
while(j >= 0 && arr[j] > element)
{
arr[j + 1] = arr[j];
j = j - 1;
}
//For loop
for(; j >= 0; j--)
{
if(arr[j] > element)
{
arr[j + 1] = arr[j];
}
}
Full code if anyone needs
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> sortArr(vector<int> arr, int n)
{
int i, j, element;
for(i = 1; i < n; i++)
{
element = arr[i];
j = i - 1;
while(j >= 0 && arr[j] > element)
{
arr[j + 1] = arr[j];
j = j - 1;
}
/*for( ; j >= 0 ; j--)
{
if(arr[j] > element){
arr[j + 1] = arr[j];
}
}*/
arr[j + 1] = element;
}
return arr;
}
};
int main()
{
vector<int> s(4);
for(int i = 0; i < 4; i++)
{
cin >> s[i];
}
Solution ob;
vector<int> v = ob.sortArr(s, 4);
for(auto i : v)
{
cout << i << ' ';
}
cout << endl;
return 0;
}
Your while and for loops aren't equivalent. With your for loop, j always end up at 0 because there is no equivalence to the && arr[j] > element check. This corrupts the vector content because you'll overwrite index 0.
Equivalent for loop:
for( ; j >= 0 && arr[j] > element; j--)
{
arr[j + 1] = arr[j];
}
Both are not equivalent, if you look at this:
while (j >= 0 && arr[j] > element)
{
arr[j + 1] = arr[j];
j = j - 1;
}
It stops as soon as arr[j] > element. But this does not:
for( ; j >= 0 ; j--)
{
if(arr[j] > element){
arr[j + 1] = arr[j];
}
}
As it continue to run beyond arr[j] > element. So the equivalent will be:
for( ; j >= 0 && (arr[j] > element) ; j--)
{
arr[j + 1] = arr[j];
}
The loops are written with different logical conditions of break. Look at while:
while (j >= 0 && arr[j] > element)
This loop will break when j is lower than 0 or the arr[j] is lower than element. So if you meet the first element that is equal to/higher than arr[j], the loop will break.
And now let's see the for loop:
for( ; j >= 0 ; j--)
In this case the only condition is the countdown of value j. But if you find the element equal to / higher than arr[j], meaning this won't be fulfilled:
if(arr[j] > element){
the loop will continue anyways until j isn't lower than 0.
What would repair your code snippet is adding break instruction:
for ( ; j >= 0; j--) {
if(arr[j] > element) {
arr[j + 1] = arr[j];
} else {
break; // the loop will stop, just like the while loop does
}
}
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
I am trying to sort an array using the code below:-
The expected output should be an array which is sorted in ascending order.
But when i tried to run this code the output comes out to be 59 (6 times)
I have tried debugging it added a watch at first array declaration and added a breakpoint on the first for loop it gives out the error to be :-
->->error-begin
A syntax error in expression, near `A[6]={31,41,59,26,41,58}'.
#include<iostream>
using namespace std;
int main()
{
int A[6]={31,41,59,26,41,58};;
int j;
int length = 6;
for(j=2;j<length;j++)
{
int key;
key = A[j];
int i;
i=j-1;
while(i>0 && A[i]>key)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
cout<<A[j];
}
return 0;
}
Update:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A[6] = { 31, 41, 59, 26, 41, 58 };
int temp;
int j;
int length = 6;
for (j = 2; j < length; j++) {
int key;
key = A[j];
int i;
i = j - 1;
while (i > 0 && A[i] > key) {
temp = A[i + 1];
A[i + 1] = A[i];
A[i] = temp;
i = i - 1;
}
A[i + 1] = key;
}
cout << A[j];
return 0;
}
It's working is supposed to be like a bubble sort I do know about
std::sort(std::begin(A), std::end(A));
But I am curious why this code isn't working, I have already tried looking up wiki and other sites for similar code but i can't seem to find anything relevant.
Replace:
while(i>0 && A[i]>key)
by:
while (i >= 0 && A[i] > key)//notice the equality sign!
It was just checking till the 1st index while the zeroth index was not touched
And you might want to print the contents of the array like this:
for(int i=0;i<6;i++)
cout << A[i]<<" ";
For starters this loop
for (j = 2; j < length; j++) {
^^^^^
has an incorrect initial setting. It will not sort an array that has only two elements or the second element will be never swapped with the first element if the second element is less than the first element.
It would be correctly to write the statement like
for (j = 1; j < length; j++) {
^^^^^
The inner loop
while (i > 0 && A[i] > key) {
does not touch the element A[0] due to the condition i > 0, Thus the subcondition A[0] > key will be never checked.
It is better instead of swapping each pair of elements that satisfy the condition just to copy elements and then to write the "added" element in the required position.
The program can look the following way.
#include <iostream>
int main()
{
int a[] = { 31, 41, 59, 26, 41, 58 };
const size_t N = sizeof(a) / sizeof(*a);
for (int x : a) std::cout << x << ' ';
std::cout << std::endl;
for (size_t i = 1; i < N; i++)
{
int value = a[i];
size_t j = i;
for (; j != 0 && value < a[j - 1]; --j)
{
a[j] = a[j - 1];
}
if (j != i) a[j] = value;
}
for (int x : a) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The program output is
31 41 59 26 41 58
26 31 41 41 58 59
# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
foreach (gap in gaps)
# Do an insertion sort for each gap size.
for (i = gap; i < n; i += 1)
temp = a[i]
for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
a[j] = a[j - gap]
a[j] = temp
this is the pseudocode in Wikipedia page.
I'm not sure about that if my c++ code is correct according to it. Here is my code:
void shellSort(int *array, int array_size)
{
int e, i, j, temp;
for(e = 0; e < array_size; e++)
{
for( i = e; i < array_size; i++)
{
temp = array[i];
for( j = i; j >= e && array[j - e] > temp; j -= e)
{
array[j] = array[j-e];
}
array[j] = array[temp];
}
}
}
And here is my test code:
int main()
{
int sizes[9] = {9,3,5,7,1,0,6,2,4};
int size = 0;
shellSort(sizes,size);
for(int i=0;i<size;i++)
{
cout << sizes[i] << endl;
}
return 0;
}
but it shows nothing on the screen.
Okay, let's take this from the top
void shellSort(int *array, int array_size)
{
Your code completely omitted the needed gaps array
const int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1};
int e, i, j, temp;
The outer loop needs to be across gaps rather than 0 to array_size
for(e = 0; e < sizeof(gaps)/sizeof(int); ++e)
{
int gap = gaps[e];
You need to use the gap from the gaps array in the inner loop
for( i = gap; i < array_size; ++i)
{
temp = array[i];
for( j = i; j >= gap && array[j - gap] > temp; j -= gap)
{
array[j] = array[j-gap];
}
You need to store temp back into the array
array[j] = temp;
}
}
}
NB: I don't have a compiler to hand right now, so I haven't checked that, but I think it's right.
Also, a few minor points, this:
int e, i, j, temp;
is bad practice, instead declare each variable as you use it, i.e. do this instead:
for( int i = gap; i < array_size; ++i)
{
int temp = array[i];
For some reason (no comments were given), my first answer was deleted (typo - you set size to 0, not 9). The question wondered why "it shows nothing on the screen". If you set size to 0, what do you expect a for loop to do when it iterates from 0 to < size???
Before looking at the algorithm, your parameters must be correct. Start there. If SOMETHING now gets dumped to the screen, NOW you can start debugging the algorithm (if the output was wrong). If the output is right, then your algorithm is probably okay.
If I am wrong about this, PLEASE POST A COMMENT TO MY ANSWER. Don't just "delete" it!?!