0% found this document useful (0 votes)
18 views4 pages

All

Uploaded by

abuhoraira10154
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

All

Uploaded by

abuhoraira10154
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

int binary_search(int a[], int low, int high, int key)

{
if (low <= high)
{
int mid = low + ((high - low) / 2);
if (a[mid] == key)
return mid;
if (a[mid] > key)
return binary_search(a, mid + 1, high, key);
return binary_search(a, low, mid - 1, key);
}
else
return -1;
}
class Dynamic_array
{
public:
int sz;
int *a;
int max;
D_ar()
{
sz = 0;
max = 1;
a = new int[max];
}
void increase()
{
max = max * 2;
int *tm = new int[max];
for (int i = 0; i <= sz; i++)
{
tm[i] = a[i];
}
delete[] a;
a = tm;
}
void decrease()
{
if (max == 1)
{
return;
}
max = max / 2;
int *tm = new int[max];
for (int i = 0; i < sz; i++)
{
tm[i] = a[i];
}
delete[] a;
a = tm;
}
void remove()
{
sz--;
if (sz * 2 == max)
{
decrease();
}
}
void add(int n)
{
if (sz == max)
{
increase();
}
a[sz] = n;
sz++;
}
void print()
{
for (int i = 0; i < sz; i++)
{
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < max; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
};
void bubble(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int co = 0;
for (int j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
co = 1;
swap(a[j], a[j + 1]);
}
}
if (co == 0)
{
return;
}
}
}
void insertion_sort(int a[], int n)
{
for (int i = 1; i < n; ++i)
{
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
void selection_sort(int a[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; ++j)
{
if (a[j] < a[min_idx])
{
min_idx = j;
}
}
// Swap the found minimum element with the first element
swap(a[min_idx], a[i]);
}
}
void sieve(int n)
{
int a[n + 1];
for (int i = 0; i < n + 1; i++)
{
a[i] = 0;
}
for (int i = 2; i < n + 1; i++)
{
if (a[i] == 0)
{
for (int j = i + i; j < n + 1; j += i)
{
a[j] = 1;
}
}
}
for (int i = 0; i < n + 1; i++)
{
cout << a[i] << " ";
}
}
void merging(int a[], int start, int end, int mid)
{
int i = start, j = mid + 1, k = 0;
int tm[end - start + 1];
while (i <= mid && j <= end)
{
if (a[i] > a[j])
tm[k++] = a[j++];
else
tm[k++] = a[i++];
}
while (i <= mid)
{
tm[k++] = a[i++];
}
while (j <= end)
{
tm[k++] = a[j++];
}
for (int i = 0; i < end - start + 1; i++)
{
a[i + start] = tm[i];
}
}

void merge(int a[], int start, int end)


{
if (start < end)
{
int mid = start + (end - start) / 2;
merge(a, start, mid);
merge(a, mid + 1, end);
merging(a, start, end, mid);
}
else
return;
}

You might also like