Why didn't my alternative sorting algorithm work? - c++

I was trying to implement a sorting code so i tried something completely without looking at any other reference codes or anything. Please tell me why my code doesnt show any output? It just runs for sometime and then stops suddenly.
I want to know where i am going wrong. I wanted to take any array as an input and sort the numbers in it in ascending order. So i just iterated throughput the array and compared adjacent elements and swaped them. Then i tried printing the numbers using their indices but it did not print anything on the screen.
#include <iostream>
using namespace std;
int main() {
int arr[6]={1,23,2,32,4,12};
int i=0;
while(i<6)
{
if(arr[i]>arr[i+1])
{
int x = arr[i];
arr[i]=arr[i+1];
arr[i+1]=x;
}
else
continue;
i++;
}
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<arr[4];
cout<<arr[5];
return 0;
}
I expected that the numbers will be printed in ascending order but nothing happened. And also tell me how to print an array all at once.
Thank you

Your sorting algorithm doesn't work because it performs only one pass of a variant of Bubble Sort or Insertion Sort. There has to be one more loop wrapped around your loop to repeat the operation N-1 times.
There are a number of ways to explain why multiple passes are required. Here is one explanation. Whenever we perform this step:
if (arr[i] > arr[i+1])
{
int x = arr[i];
arr[i] = arr[i+1];
arr[i+1] = x;
}
we transfer the arr[i+1] element into the arr[i] position. By doing so, we effectively skip the arr[i+1] element.
Here is what I mean. Suppose arr[i] is called x, arr[i+1] is called y and arr[i+2] is called z. We start with xyz, and exchange x and y to make yxz. But then on the next iteration of the loop, we compare x and z and have forgotten about y; x has moved forward in the array, pushing down y. Why is that a problem? Because y and z have not been compared; and those two are not necessarily in sorted order!
Suppose we have { 3, 2, 0 }. We compare 3 and 2, and swap them, giving us { 2, 3, 0}. Then we move on to comparing 3 and 0: we swap those and get { 2, 0, 3 }. See the problem? We neglected to deal with 2 and 0. That requires another pass through the array.
There is a family of algorithms which work by repeatedly scanning through an array and exchanging items. I suggest studying the following of the common algorithms in this family: insertion sort, selection sort and Shell sort. Also look at bubble sort, in order to understand why it's a poor algorithm compared to either insertion or selection sort that it is closely related to.

your loop condition is incorrect - the last iteration will compare arr[5] and arr[6] which gives index out of bound.
you update your iterator "i" only if you swap, so if your loop encounters the case where arr[i] <= arr[i+1], your iterator will never get updated and your program will run infinitely.
your algorithm implements just a first iteration of bubble sort i.e. it bubbles up (from left to right) the largest number and stops. so the final array looks like [1, 2, 23, 4, 12, 32]

Related

I am trying my sorting method, which works well with data with no repeates entries, but am getting random numbers in place of repeated numbers?

I have been trying a sorting method in which I subtract each number stored in an array by other elements in the same array. Then, I saw a pattern that the number of differences which come to be negative, is the rank or position of element in the Sorted one. But, things go wrong when I am using repeated entries.
My basic method is :
Take every element of the SampleArray.
subtract it from every element of the SampleArray
check if the difference comes to be negative.
if it is then, increase a variable called counter.
And use this counter as the position of element in sorted array.
For example: lets take (5,2,6,4)
first take 5, subtract it from each of the numbers which will give results (0,-3,1,-1), so counter will become 2, which will be the index of 5 in the sorted Array. And repeat it for each of the elements.
for 5, counter will be 2.
for 2, counter will be 0.
for 6, counter will be 3.
for 4, counter will be 1.
And hence the sorted Array will be {2,4,5,6}.
First, see the code :
#include <iostream>
using namespace std;
void sorting(int myArray[], int sizeofArray);
int main()
{
int checkArray[] = {5,4,2,20,12,13,8,6,10,15,0}; //my sample Arry
int sized;
sized=sizeof checkArray/sizeof(int);//to know the size
cout << sized << endl;
sorting(checkArray, sized);
}
void sorting(int myArray[], int sizeofArray)
{
int tempArray[sizeofArray];
for (int i=0; i<sizeofArray; i++)
{
int counter=0;
for (int j=0;j<sizeofArray; j++ )
{
int checkNum = myArray[j]-myArray[i];
if (checkNum<0)
counter++; //to know the numbers of negatives
else
counter+=0;
}
tempArray[counter]=myArray[i];
}
for (int x=0;x<sizeofArray; x++)
{
cout << tempArray[x] << " " ;
}
}
Now, if we run this program with entries with no repetitions then, it sorts out the array, But if we use repeated entries like
int checkArray[] = {8,2,4,4,6}
the tempArray gets its first element as 2 as counter will be zero.
the tempArray gets its second element as 4 as counter will be 1.
but, the tempArray can't get its third one as counter will be still 1, and thus prints some randomNo in place of this. (here the things go wrong).
Can you please suggest a method to solve this?
This is an odd way of writing insertion sort, https://en.wikipedia.org/wiki/Insertion_sort
I would assume you can change your condition to:
if (checkNum<0 || (checkNum==0 && j<i))
But I would suggest using a proper sorting routine instead
The idea is to separate duplicates by saying that if the values are the same we sort according to their order in the sequence; as if the sequence was a pair of the value and the sequence number (0, 1, 2, 3, 4, 5, ...).
The issue here is that for any 2 equally sized numbers the nested loop will return the same counter value. Thus for such a counter value tempArray[counter + 1] will never be initialized.
The way to solve this would be to maintain a vector<bool> denoting what each position had been written and write to the next valid position if that is the case.
But supporting a second vector is just going to make your O(n2) code slower. Consider using sort instead:
sort(begin(checkArray), end(checkArray))

Is this code a bubble sorting program?

I made a simple bubble sorting program, the code works but I do not know if its correct.
What I understand about the bubble sorting algorithm is that it checks an element and the other element beside it.
#include <iostream>
#include <array>
using namespace std;
int main()
{
int a, b, c, d, e, smaller = 0,bigger = 0;
cin >> a >> b >> c >> d >> e;
int test1[5] = { a,b,c,d,e };
for (int test2 = 0; test2 != 5; ++test2)
{
for (int cntr1 = 0, cntr2 = 1; cntr2 != 5; ++cntr1,++cntr2)
{
if (test1[cntr1] > test1[cntr2]) /*if first is bigger than second*/{
bigger = test1[cntr1];
smaller = test1[cntr2];
test1[cntr1] = smaller;
test1[cntr2] = bigger;
}
}
}
for (auto test69 : test1)
{
cout << test69 << endl;
}
system("pause");
}
It is a bubblesort implementation. It just is a very basic one.
Two improvements:
the outerloop iteration may be one shorter each time since you're guaranteed that the last element of the previous iteration will be the largest.
when no swap is done during an iteration, you're finished. (which is part of the definition of bubblesort in wikipedia)
Some comments:
use better variable names (test2?)
use the size of the container or the range, don't hardcode 5.
using std::swap() to swap variables leads to simpler code.
Here is a more generic example using (random access) iterators with my suggested improvements and comments and here with the improvement proposed by Yves Daoust (iterate up to last swap) with debug-prints
The correctness of your algorithm can be explained as follows.
In the first pass (inner loop), the comparison T[i] > T[i+1] with a possible swap makes sure that the largest of T[i], T[i+1] is on the right. Repeating for all pairs from left to right makes sure that in the end T[N-1] holds the largest element. (The fact that the array is only modified by swaps ensures that no element is lost or duplicated.)
In the second pass, by the same reasoning, the largest of the N-1 first elements goes to T[N-2], and it stays there because T[N-1] is larger.
More generally, in the Kth pass, the largest of the N-K+1 first element goes to T[N-K], stays there, and the next elements are left unchanged (because they are already increasing).
Thus, after N passes, all elements are in place.
This hints a simple optimization: all elements following the last swap in a pass are in place (otherwise the swap wouldn't be the last). So you can record the position of the last swap and perform the next pass up to that location only.
Though this change doesn't seem to improve a lot, it can reduce the number of passes. Indeed by this procedure, the number of passes equals the largest displacement, i.e. the number of steps an element has to take to get to its proper place (elements too much on the right only move one position at a time).
In some configurations, this number can be small. For instance, sorting an already sorted array takes a single pass, and sorting an array with all elements swapped in pairs takes two. This is an improvement from O(N²) to O(N) !
Yes. Your code works just like Bubble Sort.
Input: 3 5 1 8 2
Output after each iteration:
3 1 5 2 8
1 3 2 5 8
1 2 3 5 8
1 2 3 5 8
1 2 3 5 8
1 2 3 5 8
Actually, in the inner loop, we don't need to go till the end of the array from the second iteration onwards because the heaviest element of the previous iteration is already at the last. But that doesn't better the time complexity much. So, you are good to go..
Small Informal Proof:
The idea behind your sorting algorithm is that you go though the array of values (left to right). Let's call it a pass. During the pass pairs of values are checked and swapped to be in correct order (higher right).
During first pass the maximum value will be reached. When reached, the max will be higher then value next to it, so they will be swapped. This means that max will become part of next pair in the pass. This repeats until pass is completed and max moves to the right end of the array.
During second pass the same is true for the second highest value in the array. Only difference is it will not be swapped with the max at the end. Now two most right values are correctly set.
In every next pass one value will be sorted out to the right.
There are N values and N passes. This means that after N passes all N values will be sorted like:
{kth largest, (k-1)th largest,...... 2nd largest, largest}
No it isn't. It is worse. There is no point whatsoever in the variable cntr1. You should be using test1 here, and you should be referring to one of the many canonical implementations of bubblesort rather than trying to make it up for yourself.

Finding maximum values of rests of array

For example:
array[] = {3, 9, 10, **12**,1,4,**7**,2,**6**,***5***}
First, I need maximum value=12 then I need maximum value among the rest of array (1,4,7,2,6,5), so value=7, then maxiumum value of the rest of array 6, then 5, After that, i will need series of this values. This gives back (12,7,6,5).
How to get these numbers?
I have tried the following code, but it seems to infinite
I think I'll need ​​a recursive function but how can I do this?
max=0; max2=0;...
for(i=0; i<array_length; i++){
if (matrix[i] >= max)
max=matrix[i];
else {
for (j=i; j<array_length; j++){
if (matrix[j] >= max2)
max2=matrix[j];
else{
...
...for if else for if else
...??
}
}
}
}
This is how you would do that in C++11 by using the std::max_element() standard algorithm:
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
int arr[] = {3,5,4,12,1,4,7,2,6,5};
auto m = std::begin(arr);
while (m != std::end(arr))
{
m = std::max_element(m, std::end(arr));
std::cout << *(m++) << std::endl;
}
}
Here is a live example.
This is an excellent spot to use the Cartesian tree data structure. A Cartesian tree is a data structure built out of a sequence of elements with these properties:
The Cartesian tree is a binary tree.
The Cartesian tree obeys the heap property: every node in the Cartesian tree is greater than or equal to all its descendants.
An inorder traversal of a Cartesian tree gives back the original sequence.
For example, given the sequence
4 1 0 3 2
The Cartesian tree would be
4
\
3
/ \
1 2
\
0
Notice that this obeys the heap property, and an inorder walk gives back the sequence 4 1 0 3 2, which was the original sequence.
But here's the key observation: notice that if you start at the root of this Cartesian tree and start walking down to the right, you get back the number 4 (the biggest element in the sequence), then 3 (the biggest element in what comes after that 4), and the number 2 (the biggest element in what comes after the 3). More generally, if you create a Cartesian tree for the sequence, then start at the root and keep walking to the right, you'll get back the sequence of elements that you're looking for!
The beauty of this is that a Cartesian tree can be constructed in time Θ(n), which is very fast, and walking down the spine takes time only O(n). Therefore, the total amount of time required to find the sequence you're looking for is Θ(n). Note that the approach of "find the largest element, then find the largest element in the subarray that appears after that, etc." would run in time Θ(n2) in the worst case if the input was sorted in descending order, so this solution is much faster.
Hope this helps!
If you can modify the array, your code will become simpler. Whenever you find a max, output that and change its value inside the original array to some small number, for example -MAXINT. Once you have output the number of elements in the array, you can stop your iterations.
std::vector<int> output;
for (auto i : array)
{
auto pos = std::find_if(output.rbegin(), output.rend(), [i](int n) { return n > i; }).base();
output.erase(pos,output.end());
output.push_back(i);
}
Hopefully you can understand that code. I'm much better at writing algorithms in C++ than describing them in English, but here's an attempt.
Before we start scanning, output is empty. This is the correct state for an empty input.
We start by looking at the first unlooked at element I of the input array. We scan backwards through the output until we find an element G which is greater than I. Then we erase starting at the position after G. If we find none, that means that I is the greatest element so far of the elements we've searched, so we erase the entire output. Otherwise, we erase every element after G, because I is the greatest starting from G through what we've searched so far. Then we append I to output. Repeat until the input array is exhausted.

Why Bubble Sort needs nested loops?

I am going to start the new question. I posed the question yesterday and wanted to know what's the problem in my program. The program is given below and you people pointed out that this following program does only one pass of the sorting and needs an outer loop as well. At that time I was good like OK. But again when I looked the program I got confused and need to ask Why we need Outer loop as well for the sort since only a single loop can do the sorting(In my opinion). First see program below then I present my logic at the end of the program.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int number[10];
int temp = 0;
int i = 0;
cout << "Please enter any ten numbers to sort one by one: "
<< "\n";
for (i = 0; i < 10; i++)
{
cin >> number[i];
}
i = 0;
for (i = 0; i < 9; i++)
{
if (number[i] > number[i + 1])
{
temp = number[i + 1];
number[i + 1] = number[i];
number[i] = temp;
}
}
i = 0;
cout << "The sorted numbers are given below:"
<< "\n";
for (i = 0; i < 10; i++)
{
cout << number[i] << "\n";
}
getch();
}
I think the ONLY loop with the bubble condition should do the sorting. Look at the following loop of the program:
for (i=0;i<9;i++)
if(number[i]>number[i+1])
{
temp=number[i+1];
number[i+1]=number[i];
number[i]=temp;
}
Now I explain what I am thinking what this loop "should" do. It will first compare number[0] with number[1]. If the condition is satisfied it will do what is in IF statement's body. Then i will be incremented by 1(i++). Then on next iteration the values compared will be number[1] with number[2]. Then why it does not happen and the loop exits after only pass? In other words may be I'm trying to ask IF statement does not repeat itself in for loop? In my opinion it does. I'm very thankful for help and views, my question might be of small level but that is how I will progress.
Let me give you an example let's only take 3 numbers. So you input
13, 3 ,1
Now you start sorting how you did it. so it compares 13 and 3
13 > 3 so switch both of them.
now we have.
3, 13, 1
Now it'll compare as you said the next pair = 13 and 1
13 > 1 so the new order would be
3, 1, 13
now your loop is finished and you missed to compare 3 and 1
Actually the first loop only sorts the greatest number!
since only a single loop can do the sorting(In my opinion)
This is not correct. Without getting to details, a constant number of loops is not enough to sort, since sorting is Omega(nlogn) problem. Meaning, an O(1) (constant, including 1) number of loops is not enough for it - for any algorithm1,2.
Consider the input
5, 4, 3, 2, 1
a single loop of bubble sort will do:
4, 5, 3, 2, 1
4, 3, 5, 2, 1
4, 3, 2, 5, 1
4, 3, 2, 1, 5
So the algorithm will end up with the array: [ 4, 3, 2, 1, 5], which is NOT sorted.
After one loop of bubble sort, you are only guaranteed to have the last element in place (which indeed happens in the example). The second iteration will make sure the 2 last elements are in place, and the nth iteration will make sure the array is indeed sorted, resulting in n loops, which is achieved via a nested loop.
(1) The outer loop is sometimes hidden as a recursive call (quick sort is an example where it happens) - but there is still a loop.
(2) Comparisons based algorithms, to be exact.
For bubble sorting a pass simply moves the largest element to the end of array. So you need n-1 passes to get a sorted array, thats why you need other loop. Now for your code 1 pass means
if(number[0]>number[0+1])
{
temp=number[0+1];
number[0+1]=number[0];
number[0]=temp;
}
if(number[1]>number[1+1])
{
temp=number[1+1];
number[1+1]=number[1];
number[1]=temp;
}
.....6 more times
if(number[8]>number[8+1])
{
temp=number[8+1];
number[8+1]=number[8];
number[8]=temp;
}
so as you can see IF statement repeats itself, its just that after all 9 IFs the largets element moves to the end of array
This is not correct because
The algorithm gets its name from the way smaller elements "bubble" to the top of the list. (Bubble sort)
So, at the end of the first loop, we get the smallest element. So, for complete sorting, we have to keep total n loops. (where n = total size of the numbers)

factorial array for tic tac toe

I am currently trying to teach myself C++ and programming in general. So as a beginner project i'm making a genetic algorithm that creates an optimal AI for a Tic-Tac-Toe game. I am not enrolled in any programming classes so this is not homework. I'm just really interested in AI.
So i am trying to create a multidimensional array of a factorial, in my case 9! . For example if you made one of 3! it would be array[3][6] = { {1, 2, 3}, {1, 3, 2}, {2, 3, 1}, {2, 1, 3}, {3, 2, 1}, {3, 1, 2}}. Basically 3! or 3*2*1 would be the amount of ways you could arrange 3 numbers in order.
I think that the solution should be simple yet im stuck trying to find out how to come up with a simple solution. I have tried to swap them, tried to shift them right, increment ect.. the methods that work are the obvious ones and i don't know how to code them.
So if you know how to solve it that's great. If you can give a coding format that's better . Any help is appreciated.
Also i'm coding this in c++.
You can use next_permutation function of STL
http://www.cplusplus.com/reference/algorithm/next_permutation/
I actually wrote an algorithm for this by hand once. Here it is:
bool incr(int z[NUM_INDICES]){
int a=NUM_INDICES-1;
for(int i=NUM_INDICES-2;i>=0;i--)
if(z[i]>z[i+1]) a--;
else break;
if(a==0) return false;
int b=2147483647,c;
for(int i=a;i<=NUM_INDICES-1;i++)
if(z[i]>z[a-1]&&z[i]-z[a-1]<b){
b=z[i]-z[a-1];
c=i;
}
int temp=z[a-1]; z[a-1]=z[c]; z[c]=temp;
qsort(z+a,NUM_INDICES-a,sizeof(int),comp);
return true;
}
This is the increment function (i.e. you have an array like [3,2,4,1], you pass it to this, and it modifies it to [3,4,1,2]). It works off the fact that if the last d elements of the array are in descending order, then the next array (in "alphabetical" order) should satisfy the following conditions: 1) the last d+1 elements are a permutation among themselves; 2) the d+1-th to last element is the next highest element in the last d+1 elements; 3) the last d elements should be in ascending order. You can see this intuitively when you have something like [2,5,3, 8,7,6,4,1]: d = 5 in this case; the 3 turns into the next highest of the last d+1 = 6 elements; and the last d = 5 are arranged in ascending order, so it becomes [2,5,4, 1,3,6,7,8].
The first loop basically determines d. It loops over the array backwards, comparing consecutive elements, to determine the number of elements at the end that are in descending order. At the end of the loop, a becomes the first element that is in the descending order sequence. If a==0, then the whole array is in descending order and nothing more can be done.
The next loop determines what the d+1-th-to-last element should be. We specified that it should be the next highest element in the last d+1 elements, so this loop determines what that is. (Note that z[a-1] is the d+1-th-to-last element.) By the end of that loop, b contains the lowest z[i]-z[a-1] that is positive; that is, z[i] should be greater than z[a-1], but as low as possible (so that z[a-1] becomes the next highest element). c contains the index of the corresponding element. We discard b because we only need the index.
The next three lines swap z[a-1] and z[c], so that the d+1-th-to-last element gets the element next in line, and the other element (z[c]) gets to keep z[a-1]. Finally, we sort the last d elements using qsort (comp must be declared elsewhere; see C++ documentation on qsort).
If you want a hand crafted function for generating all permutations, you can use
#include <cstdio>
#define REP(i,n) FOR(i,0,n)
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define GI ({int t;scanf("%d",&t);t;})
int a[22], n;
void swap(int & a, int & b) {
int t = a; a = b; b = t;
}
void perm(int pos) {
if(pos==n) {
REP(i,n) printf("%d ",a[i]); printf("\n");
return;
}
FOR(i,pos,n) {
swap(a[i],a[pos]);
perm(pos+1);
swap(a[pos],a[i]);
}
return;
}
int main (int argc, char const* argv[]) {
n = GI;
REP(i,n) a[i] = GI;
perm(0);
return 0;
}