Insert Sort not working - c++

I am learning sorting algorithms. I googled the insert sort code and when I tried it on my own it's not working out. Can someone please find the error in my code?
#include<iostream>
using namespace std;
int main()
{
int i,size, a[40], key;
cout << "Enter size: ";
cin >> size;
for(int o=0; o<size; o++)
{
cin >> a[o];
}
//insertion sort
for(int j = 1; j <= size-1; j++)
{
key = a[j];
i = j-1;
while((key < a[i]) && (i >= 0));
{
a[i + 1] = a[i];
i = i - 1;
}
a[i + 1] = key;
}
cout << "\nSorted list is as follows\n";
for(int o = 0; o < size; o++)
{
cout << endl << a[o];
}
}

while((key<a[i])&&(i>=0));
You have an infinite while loop here. The semi colon at the end means that the while loop body is empty. Hence i is never decremented and the loop runs forever.
Also, you need to check if the index is valid (i >= 0) before trying to access it's value.
So change the line as below.
while((i >= 0) && (key < a[i]))

Related

Count of Maximum , Passing Test cases but WA

Getting error in this code, even though it passed the basic test cases. But still, it gives the wrong answer.
Cannot find the test case where it fails, Solution to Codechef Count of maximum problem. I think a part of the code is making it fail for a certain test case(s).
Can anyone help me find the error in this code, please?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int k;
cin >> k;
for (int j = 0; j < k; j++)
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int maxCount = 0;
int number;
int index = 0;
for (int i = 0; i < n; i++)
{
int count = 0;
for (int l = 0; l < n; l++)
{
if (a[i] == a[l])
{
count++;
if (count > maxCount)
{
maxCount = count;
index = i;
}
if (count == maxCount) {
(a[i] > a[index]) ? number = a[index] : number = a[i];
}
}
}
}
cout << number << " " << maxCount << endl;
}
}
Your number variable is redundant. You need to track theindex of the elements in the array.
That means, change this line
(a[i] > a[index]) ? number = a[index] : number = a[i];
to
(a[i] > a[index]) ? index = index : index = i;
and print
std::cout << a[index] << " " << maxCount << std::endl;

C++ Dijkstra's algorithm program with initial vertices problem and resulting one less vertex

I'm working on C++ representation/implementation of Dijkstra's algorithm and I found this program online which fails to execute properly on TurboC++.
Any one know the solution? I also want to know why there is a minimum value of 31999 and the coding runs on a mobile emulator but refuses to run on PC TurboC++
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
//using namespace std;
int shortest(int, int);
int cost[10][10], dist[20], i, j, n, k, m, S[20], v, totcost, path[20], p;
int main()
{
int c;
cout << "enter no of vertices";
cin >> n;
cout << "enter no of edges";
cin >> m;
cout << "\nenter\nEDGE Cost\n";
for (k = 1; k <= m; k++)
{
cin >> i >> j >> c;
cost[i][j] = c;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
if (cost[i][j] == 0)
cost[i][j] = 31999;
cout << "enter initial vertex";
cin >> v;
cout << v << "\n";
shortest(v, n);
}
int shortest(int v, int n)
{
int min;
for (i = 1; i <= n; i++)
{
S[i] = 0;
dist[i] = cost[v][i];
}
path[++p] = v;
S[v] = 1;
dist[v] = 0;
for (i = 2; i <= n - 1; i++)
{
k = -1;
min = 31999;
for (j = 1; j <= n; j++)
{
if (dist[j] < min && S[j] != 1)
{
min = dist[j];
k = j;
}
}
if (cost[v][k] <= dist[k])
p = 1;
path[++p] = k;
for (j = 1; j <= p; j++)
cout << path[j];
cout << "\n";
//cout <<k;
S[k] = 1;
for (j = 1; j <= n; j++)
if (cost[k][j] != 31999 && dist[j] >= dist[k] + cost[k][j] && S[j] != 1)
dist[j] = dist[k] + cost[k][j];
}
}
Arrays are 0 based so all the loops from 1 to <= n are suspect.

Prime Numbers Up To A Number

Im really new to C++ and im working through the book Programming: Principles and Practice Using C++. Were working on the problem to find all prime numbers between 1 - user given number. Now I got that part down. I now understand that the sqrt(i) would make the loop shorter but, Im not sure what to check for to see if its a prime or not in my if - else statements.
#include<vector>
#include<iostream>
#include<cmath>
using namespace std;
int main(){
vector<double> prime_numbers;
double num;
cout << "Please enter a number so we can find the primes for it: " << flush;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int j = 2; j <= i; j++) {
// cout << sqrt(i) << "\t";
// Check to see if Value of i is incremented correctly
// Check to see if value of j is incremented properly before returnign to i
//cout << i <<"\t" << j << endl;
if (j == i) {
prime_numbers.push_back(i);
}
if (i % j == 0) {
break;
}
}
}
for (double x : prime_numbers)
cout << x << " | ";
return 0;
}
A very efficient way to find the prime numbers from 0 to n is using the sieve of Eratosthenes, there are many ways to do it, here is an example:
vector<bool> v(n, true);
v[0] = v[1] = false;
for (int i = 2; i*i < n; i+= 2){
if (v[i]) {
for (int k = i*i; k < n; k += i) {
v[k] = false;
}
if (i == 2)i = 1;
}
}
for(auto i = 0; i < n; ++i)
if(v[i])cout << i << ' ';
cout << endl;
The difference is that your previous primality condition ā€“ i == jā€“ is no longer true.
It is true exactly when you have examined every number from 2 to i, but with the sqrt(i) limit, you're exiting the loop much earlier.
I think the simplest change is to introduce a variable and move the push_back outside the loop (this works with either loop condition):
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume 'i' is prime until proven wrong.
for (int j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
prime_numbers.push_back(i);
}
}
That is, first decide whether something is the case, then do something with that information.
This is a useful design in very many cases.
For instance,It makes it much easier to move the primality check into a function:
bool isPrime(int x) { /* something */ }
// ...
for (int i = 2; i <= num; i++) {
if (isPrime(i)) {
prime_numbers.push_back(i);
}
}

Why doesn't this C++ insertion sort work?

I'm learning C++ and this is one of my first programs that is going to sort a list of numbers, I found the algorithm in Kenneth H. Rosen book and wrote it in C++. when I check it on the paper it seems to be correct, but in practice it has some error. For example I enter 3(enter)2(enter)1(enter)4(enter)5(enter) and it returns 3 1 1 4 5 as the answer. I don't know what is the problem, please help.
int main()
{
int i, j, s, n, k, a[50];
cout << "Enter number of numbers:\n";
cin >> n;
cout << "Enter the numbers:\n";
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (j = 2; j < n; j++) {
i = 1;
while (a[j] > a[i]) {
i = i + 1; // Here we find the proper place to(if needed) directly insert our number into the sorted part.
}
s = a[j];
for (k = 0; k < j - i - 1; k++) {
a[j - k] = a[j - k - 1];
}
a[i] = s;
}
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
_getch();
return 0;
}
I've also included the header files and namespace, not written here though. And in the case you think I have used so many variables, sorry about that, I needed them :)
Your index i should start from the first element which is 0 instead of 1.
Fixing line 11 should do the job:
for (j = 2; j < n; j++) {
i = 0;
while (a[j] > a[i]) {
Edit:
Oh, and also, your variable j should start from the second element which is index 1 instead of 2:
for (j = 1; j < n; j++) {

Piece of code doesn't give the answer I need. Suggested edits?

This code is supposed to check the input array for five consecutive '1's if found, it is supposed to add a '0' at the end as a parity bit for a simple parity bit checker.
This is the code.
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
int n, a[30], b[5] = {1, 1, 1, 1, 1}, temp = 0, count = 0;
cout << "Enter the size of input bits :";
cin >> n;
cout << endl;
cout << "Enter the input bits :";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = n; i >= 0; i--) {
if (i >= 4) {
temp = i;
for (int j = 0; j < 5; j++) {
if (a[temp] == b[j]) {
temp++;
count++;
}
}
}
}
if (count == 4) {
n = n + 1;
a[n] = 0;
}
cout << endl << endl;
for (int i = 0; i < n; i++) {
cout << a[i];
}
getch();
return 0;
}
Here is a simple logic of what you want to achieve.. let's say input array is a, it's length is n:
int counter = 0;
for(int i=0; i<n; i++) {
if(a[i] == 1)
counter++;
else
counter = 0; //need to start looking for 1's again because consecutive stream is broken
if(counter == 5) {
a[i+1] = 0; //found 5 consecutive 1's so next bit will be 0
i++; //don't need to check the next bit which is already 0
counter = 0; //resetting counter
}
}
The above code will change the array [2,3,1,1,1,1,1,3,4,5] to -> [2,3,1,1,1,1,1,0,4,5]
If you want to insert 0 at the end of the array then simply change a[i+1] = 0 to a[n+1] = 0 and remove i++;
You also need to make sure that n is not greater than the size of array.
I'll go line by line from the beginning:
change for(int i=n; i>=0; i--) to for (int i = n-1; i >= 0; i--) (n-sized array in C++ has cells in the range of [0, n-1])
change if(i>=4) to if (n >= 5)
place temp++ after if(a[temp]==b[j]){}, not inside of it.
add
if (count == 5) break;
else count = 0;
just after for(int j = 0; j < 5; j++) loop
change
if(count==4)
{
n=n+1;
a[n]=0;
}
to
if(count == 5){
a[n] = 0;
n = n+1;
}
Once again! n-sized array holds n elements on positions 0 to n-1
Of course sequence makes a difference above!
You can also write it as if (count == 5) a[n++] = 0;
And that would be all.