(Newbie) Need C++ programming help


The assignment was to write a C++ program that implements Insertion, Bubble, Merge Sorts for sorting Arrays of non-negative integers. The three Algorithms should return as output not just the sorted Array but also the number of COMPARISONS needed to sort the array. The array is has randomly generated numbers from a certain range specified by the user. A function was also needed to check if the array has been correctly sorted.



I should use the vector container from the C++ Standard Template library. I should NOT USE any other STL algorithms for sorting/merging.



I'm a beginner at C++ and this is my first assignment using C++. Please help ! ! !



  

My problems are that the function for Insertion Sort and Bubble Sort are not returning the correct number of Comparisons even though they are calculating the right number of Comparisons inside the function.



Also the function for Merge Sort I'm getting errors when initializing the array L[] and R[] .  

This are the errors I'm getting



Error 4 error C2057: expected constant expression 156  

Error 5 error C2466: cannot allocate an array of constant size 0 156  

Error 6 error C2133: 'L' : unknown size 156  

Error 7 error C2057: expected constant expression 156  

Error 8 error C2466: cannot allocate an array of constant size 0 156  

Error 9 error C2133: 'R' : unknown size 156



```
// Platform : Microsoft Visual Studio 2005 ( Visual C++ )

//Problem 1 



#include <iostream>
#include <cstdlib>
#include <vector>
#include <limits>
using namespace std;

int insertionSort (vector<int> &);
int bubbleSort (vector<int> &);
int mergeSort (vector<int> &, int , int);
void populateArrayRND (vector<int> &, int);
bool isSorted (const vector<int> &);
void printArray (const vector<int> &);

int main () 
{

	int aSize;
	int maxElem;
	

	cout << "Size of the Array : ";
	cin >> aSize;	//input size of Array
	cout << "Max element in the Array : ";
	cin >> maxElem;	//input max element of Array

	vector< int > integers(aSize);

	populateArrayRND(integers, maxElem);
	printArray(integers);



	vector<int> copy_integers_1(integers); //copy constructor
	vector<int> copy_integers_2(integers); //copy constructor
	vector<int> copy_integers_3(integers); //copy constructor

	
	
	insertionSort(copy_integers_1);
	printArray(copy_integers_1);
	cout<<"Number of Comparisons needed: "<<insertionSort(copy_integers_1)<<endl;  //wrong number of comparisons
	if (isSorted(copy_integers_1)==1)
		cout<<"Insertion Sort Array Sorted"<<endl<<endl;
	else
		cout<<"Insertion Sort Array not Sorted"<<endl<<endl;

	
	
	bubbleSort(copy_integers_2);
	printArray(copy_integers_2);
	cout<<"Number of Comparisons needed: "<<bubbleSort(copy_integers_2)<<endl; //wrong number of comparisons
	if (isSorted(copy_integers_2)==1)
		cout<<"Bubble Sort Array Sorted"<<endl<<endl;
	else
		cout<<"Bubble Sort Array not Sorted"<<endl<<endl;

	
	
	
	mergeSort(copy_integers_3, 1, aSize);
	
	cout<<endl;
	cin>>aSize;

	
	return 0;

}

void populateArrayRND ( vector<int> &A, int M)
{
	size_t i;
	size_t ArraySize = A.size();

	for ( i=0; i<ArraySize; i++ )
	{
		A[i]= rand() %M;
		
	}
	cout<<endl<<endl;
}

int insertionSort (vector<int> &A)
{	
	int i,key;
	int Comp=0;
	size_t ArraySize = A.size();

	for(int j=1; j<ArraySize; j++)
	{
		key = A[j];
		i=j-1;
		
		while((i>=0)&&(A[i]>key))
		{
			A[i+1] = A[i];
			i--;
			Comp=Comp+1;
		}
		A[i+1] = key;
		Comp++;
	
	}
	
	
	cout<<"here "<<Comp; // correct number of comparisons

	return Comp;
}

int bubbleSort (vector<int> &A)
{
	int Temp;
	int Comp=0;
	size_t ArraySize = A.size();

	for (int i=0; i<ArraySize; i++)
	{
		for (size_t j=ArraySize; j>(i+1); j--)
		{
			if (A[j-1]<A[j-2])
			{
				Temp = A[j-1];
				A[j-1] = A[j-2];
				A[j-2] = Temp;
				Comp++;
				
			}
		}
	}

	
	cout<<"here "<<Comp; //correct number of comparisons

	return Comp; 
}


int mergeSort (vector<int> &A, int p, int r)
{
	int Comp=0;
	int q =(p+r)/2;
	int n1 = (q-p+1);
	int n2 = (r-q);
	int i, j;
	const int Left_Size = n1+1;
	const int Right_Size = n2+1;
	
	int L[Left_Size], R[Right_Size]; // line 156
	
	for (i=0; i<n1; i++)
		L[i] = A[1+i-1];
	
	
	for (j=0; j<n2; j++)
		R[j] = A[q+j];
	
		
	L[n1+1]=R[n2+1]= numeric_limits<int>::max(); //sentinel

	i=j=0;

	for (int k=(p-1); k<r; k++)
	{
		if (L[i]<= R[j])
		{
			A[k] = L[i];
			i=i+1;
			Comp=Comp+1;
		}

		else
		{
			A[k] = R[j];
			j=j+1;
			Comp=Comp+1;
		}
	}
	for (int l=0; l<r; l++)
	cout<<A[l]<<" ";
	cout<<endl;
	cout<<Comp;

	return(Comp);
}



bool isSorted (const vector<int> &A)
{
	
	size_t ArraySize = A.size();
	
	for ( int i=0; i<ArraySize; i++)
	{
		if ((i>=0)&&(A[i]<=A[i+1])){
			return true;
		}
		else{
			return false;
			break;
		}
	}
}


void printArray (const vector<int> &A)
{
	size_t ArraySize = A.size();
	
	
	cout<<"Array: ";

	for (int i=0; i<ArraySize; i++)
	cout<<A[i]<<" ";

	cout<<endl<<endl;

}
```
for your insertion and bubble sort, you are returning the comparison value, but you are not assinging it to anything when that value is returned. In your main



```
insertionSort(copy_integers_1);
```

Change that to:



```
int compInsertion = 0;
...
compInsertion = insertionSort(copy_integers_1);
```

and do the same with your bubble sort.



It actually would work the way it is, but the second time you call your functions (in your cout statements in main) the arrays are already sorted.



As for your error, try this



```
int *L = new int[Left_Size];
int *R = new int[Right_Size];
```

Also, you probably don't need to declare Left\_Size or Right\_Size as const.
In C ++ 11, the code is well defined, but may not do what you expect. Exact Effects: 21.4.5 / 2:



>  Returns: `*(begin() + pos)`
>   
> 
> 
> 
> 
>  (adsbygoogle = window.adsbygoogle || []).push({});
>  
>   
> 
> if `pos < size()`
>   
> 
> 
> 
> 
>  (adsbygoogle = window.adsbygoogle || []).push({});
>  
>   
> 
> , otherwise a reference to an object of type `T`
>   
> 
> 
> 
> 
>  (adsbygoogle = window.adsbygoogle || []).push({});
>  
>   
> 
> with a value `charT()`
>   
> 
> 
> 
> 
>  (adsbygoogle = window.adsbygoogle || []).push({});
>  
>   
> 
> ; the reference value should not be changed.
> 
> 
> 



  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

So, if the string is not empty, it returns a reference to the beginning of the internal buffer. If empty, it returns a reference `char`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

with a value `0`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

whose location is implementation information. The existing solutions based on `findall` are fine for non-overlapping matches (and no doubt optimal except maybe for HUGE number of matches), although alternatives such as `sum(1 for m in re.finditer(thepattern, thestring))` (to avoid ever materializing the list when all you care about is the count) are also quite possible. Somewhat idiosyncratic would be using `subn` and ignoring the resulting string...:



```
def countnonoverlappingrematches(pattern, thestring):
  return re.subn(pattern, '', thestring)[1]

```

the only real advantage of this latter idea would come if you only cared to count (say) up to 100 matches; then, `re.subn(pattern, '', thestring, 100)[1]` might be practical (returning 100 whether there are 100 matches, or 1000, or even larger numbers).


Counting **overlapping** matches requires you to write more code, because the built-in functions in question are all focused on NON-overlapping matches. There's also a problem of definition, e.g, with pattern being `'a+'` and thestring being `'aa'`, would you consider this to be just one match, or three (the first `a`, the second one, both of them), or...?


Assuming for example that you want possibly-overlapping matches *starting at distinct spots in the string* (which then would give TWO matches for the example in the previous paragraph):



```
def countoverlappingdistinct(pattern, thestring):
  total = 0
  start = 0
  there = re.compile(pattern)
  while True:
    mo = there.search(thestring, start)
    if mo is None: return total
    total += 1
    start = 1 + mo.start()

```

Note that you do have to compile the pattern into a RE object in this case: function `re.search` does not accept a `start` argument (starting position for the search) the way *method* `search` does, so you'd have to be slicing thestring as you go -- definitely more effort than just having the next search start at the next possible distinct starting point, which is what I'm doing in this function. check out the intersect function.
here is one approach:
% generate a rectangular boundry
rectx = [0.1 0.1 0.9 0.9];
recty = [0.1 0.5 0.5 0.1];
rect = polyshape(rectx,recty);

% initialize a figure for display purposes
figure(1);clf
titles = [...
 "all lines";...
 "partially within";...
 "exclusively within"];
for i = 1:3
 subplot(1,3,i)
 hold on
 title(titles(i))
 plot(rect)
 xlim([0 1])
 ylim([0 1])
end

% define the number of line segments to generate
nlines = 25;

% initialize a structure to store the lines (if you need the data later)
lines = struct();

% generate each line, calculate it's intersection conditions, and plot
for i=1:nlines
 
 % generate points for a random line segment
 lines(i).points = rand(2);
 
 % section the line into parts at intersection with the rectangle
 [in, out] = intersect(rect, lines(i).points);
 
 % plot all the lines that were generated
 subplot(1,3,1)
 line(lines(i).points(:,1),lines(i).points(:,2))
 
 % plot lines that are partially within the boundary
 if isempty(in)==0
 subplot(1,3,2)
 line(lines(i).points(:,1),lines(i).points(:,2))
 end
 
 % plot lines that are exclusively within the boundary
 if isempty(out)==1
 subplot(1,3,3)
 line(lines(i).points(:,1),lines(i).points(:,2))
 end
end
here is the output: not sure i understood. are you having problems with this code?

if yes, i think you’re using the wrong comparison operator (not = but ==). more information: [c++ friend functions](http://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm) `stream`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

of `PriorityBlockingQueue`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

follows the order `Iterator`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

, which according to the [documentation](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=) :



>  The iterator provided in the iterator () method is not guaranteed to traverse the PriorityBlockingQueue elements in any particular order.
> 
> 
> 


If you want order of precedence, you need `poll`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

items from `PriorityBlockingQueue`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

.



  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  


```
PriorityBlockingQueue<Integer> pq = new PriorityBlockingQueue<>();
pq.add(5);
pq.add(8);
pq.add(3);

System.out.println("-- Try 1 --");
pq.stream().forEach(System.out::println);

System.out.println("-- Try 2 --");
IntStream.range(0, pq.size()).map(i -> pq.poll()).forEach(System.out::println);

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

Conclusion (this may depend on Java implementation):



```
-- Try 1 --
3
8
5
-- Try 2 --
3
5
8

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
``` hi [@nathan\_lively](/u/nathan_lively) - i’m not as familiar with the limitations of the bubble api, but i think i see two problems that might be causing the error.

the list you’re sending should look like this: ["1:1 matched reference"]. each array value needs to be wrapped in quotes.

you probably also don’t need quo… ?solution:

step 1
in this problem we need to clarify why shaker sort is efficient for sorting lists that are already in close to the correct order.
step 2
shaker sort is a sorting algorithm which compares pairs of adjacent elements, interchanging them if they are not in order. it moves one element at a time till it has reached its proper place in the ordered list by comparing element adjacent to it and also it sorts elements in both directions as it passes through the list. 
for a list that is already close to the correct order, shaker sort will only find the elements that are not in correct place and then put these elements in its correct position. since there are going to be a few elements which are not in their correct position therefore it will take less time for shaker sort to correct the order of the elements. >> [x,y] = ismember(a,b);
>> [~,z] = sort(y(x));
>> v = find(x);
>> r = reshape(v(z),2,[]).'
r =
 2 9
 4 8
 5 7 Hi mgfranz,We are happy to announce the release of Photoshop CC 19.1.5.This update includes the fix for [Photoshop CC 2018: An integer between 96 and 8 is required. Closest value inserted. "Could not complete your request bec…](https://community.adobe.com/external-link.jspa?url=https%3A%2F%2Ffeedback.photoshop.com%2Fphotoshop_family%2Ftopics%2Fphotoshop-cc-2018-an-integer-between-96-and-8-is-required-closest-value-inserted)Once the update is installed, to allow Photoshop to manage memory the temporary fix needs to be removed.See this: [Error while accessing performance preferences - 'An integer between 96 and 8 is required.'](https://community.adobe.com/external-link.jspa?url=https%3A%2F%2Fhelpx.adobe.com%2Fphotoshop%2Fkb%2Finvalid-numeric-entry-integer-96-8-required-photoshop.html)Here's a list of what's new in this release: [Fixed issues in Adobe Photoshop CC](https://community.adobe.com/external-link.jspa?url=https%3A%2F%2Fhelpx.adobe.com%2Fphotoshop%2Fkb%2Ffixed-issues.html)...