In: Computer Science
C
Write a function int sort(int** arr, int n) that takes as input an array of int pointers, multiplies the ints the pointers point to by -1, and then sorts the array such that the values pointed to by the pointers are in decreasing order. For example, if the array is size 10 the pointer at index 0 will point to the largest value after multiplying by -1 and the pointer at index 9 will point to the smallest value after multiplying by -1. If the input is invalid the function should return 1. Otherwise, the function should return 0. Note- a pointer to the array size is passed to the function, NOT the actual size.
int sort(int** arr, int n)
(input is a double pointer)
//bubble sort
#include<iostream>
using namespace std;
int sort(int **arr, int n)
{
try{
if(n<=0)
throw 1;
}
catch(...)
{
return 1;
}
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(*arr[i]*-1>*arr[j]*-1)
{
int
temp=*arr[j];
*arr[j]=*arr[i];
*arr[i]=temp;
}
return 0;
}
int main()
{
int n=10;
int array[10]={-12,23,2,34,93,-99,200,104,-122,20};
int *arr[10];
for(int i=0;i<n;i++)
arr[i]=&array[i];
int r=sort(arr,n);
if(!r){
for(int i=0;i<n;i++)
cout<<*arr[i]<<" ";
}
else
cout<<"wrong input";
}
//output;
//sai@sai-Lenovo-G50-80:~/C$ ./bubble_sort
//-122 -99 -12 2 20 23 34 93 104 200