Você está na página 1de 26

Kth smallest number in an array

#include <iostream>

using namespace std;

int randomSelect(int *array, int lower_lim, int upper_lim, int order) {

if(lower_lim == upper_lim)

return array[lower_lim];

int pivot = randomPartition(array, lower_lim, upper_lim), x = pivot - lower_lim + 1;

return order <= x ? randomSelect(array, lower_lim, x, order) : randomSelect(array, x+1, upper_lim, order
- x);

int randomPartition(int *array, int lower_lim, int upper_lim) {

int pivot = rand() % (upper_lim - lower_lim + 1);

swap(&array[pivot], &array[lower_lim]);

return partition(array, lower_lim, upper_lim);

int partition(int *array, int lower_lim, int upper_lim) {

int pivot = array[lower_lim];


int i = lower_lim+1;

for(int j = lower_lim+1; j <= upper_lim; j++) {

if(array[j] < pivot) {

swap(&array[i++], &array[j]);

swap(&array[lower_lim], &array[i-1]);

return i-1;

int swap(int *i, int *j) {

int temp = *i;

*i = *j;

*j = temp;

int main() {

int array[5] = {1, 5, 3, 2, 4};

cout << "3rd Order Statistic: " << randomSelect(array, 1, 5, 3);


return 0;

Output
3rd Order Statistic: 3
Radix Sort using Counting Sort
#include <iostream>

using namespace std;

long int getMaxima(long int items[], int numItems) {

long int max = items[0];

for(int i = 0; i < numItems; i++)

if(items[i] > max)

max = items[i];

return max;

void countingSort(long int items[], int numItems, int exponent) {

long int output[numItems];

int count[10] = {0}, i;

for(i = 0; i < numItems; i++)

count[(items[i]/exponent) % 10] += 1;

for(i = 1; i < 10; i++)

count[i] += count[i-1];

for(i = numItems-1; i >= 0; i--) {

int index = (items[i]/exponent) % 10;

if(count[index] > 0) {

output[count[index]-1] = items[i];

count[index] -= 1;

}
for(i = 0; i < numItems; i++)

items[i] = output[i];

void sort(long int *items, int numItems) {

long int maximum = getMaxima(items, numItems);

for(int exponent = 1; maximum/exponent > 0; exponent *= 10)

countingSort(items, numItems, exponent);

int main() {

long int a[5] = {1, 10, 1};

sort(a, 3);

for(int i = 0; i < 3; i++)

cout << a[i] << " ";

cout << endl;

return 0;

Output
1 10 22 36 498
Bucket Sort
#include<iostream>

#include<vector>

#include<algorithm>

using namespace std;

void display(float *array, int size) {

for(int i = 0; i<size; i++)

cout << array[i] << " ";

cout << endl;

void bucketSort(float *array, int size) {

vector<float> bucket[size];

for(int i = 0; i<size; i++) { //put elements into different buckets

bucket[int(size*array[i])].push_back(array[i]);

for(int i = 0; i<size; i++) {

sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors

int index = 0;

for(int i = 0; i<size; i++) {

while(!bucket[i].empty()) {

array[index++] = *(bucket[i].begin());
bucket[i].erase(bucket[i].begin());

int main() {

int n;

cout << "Enter the number of elements: ";

cin >> n;

float arr[n]; //create an array with given number of elements

cout << "Enter elements:" << endl;

for(int i = 0; i<n; i++) {

cin >> arr[i];

cout << "Array before Sorting: ";


display(arr, n);
bucketSort(arr, n);

cout << "Array after Sorting: ";

display(arr, n);

Output
Enter the number of elements: 5
Enter elements:

.12 .08 .28 .1 .78

Array before Sorting: 0.12 0.08 0.28 0.1 0.78

Array after Sorting: 0.08 0.1 0.12 0.28 0.78


Longest Common Subsequence
#include <iostream>

#include <cstring>

using namespace std;

int max(int a, int b)

return (a > b)? a : b;

int lcs( char *X, char *Y, int m, int n )

if (m == 0 || n == 0)

return 0;

if (X[m-1] == Y[n-1])

return 1 + lcs(X, Y, m-1, n-1);

else

return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

int main() {

char x[] = "ABCBDAB", y[] = "BDCABA";

int m = strlen(x), n = strlen(y);

cout << "Longest Common Subsequence: " << lcs(x, y, m, n) << endl;
return 0;

Output
Longest Common Subsequence: 4
Knapsack Problem
#include <bits/stdc++.h>

using namespace std;

// Structure for an item which stores weight and corresponding

// value of Item

struct Item

int value, weight;

// Constructor

Item(int value, int weight) : value(value), weight(weight)

{}

};

// Comparison function to sort Item according to val/weight ratio

bool cmp(struct Item a, struct Item b)

double r1 = (double)a.value / a.weight;

double r2 = (double)b.value / b.weight;

return r1 > r2;

// Main greedy function to solve problem

double fractionalKnapsack(int W, struct Item arr[], int n)

// sorting Item on basis of ratio

sort(arr, arr + n, cmp);

// Uncomment to see new order of Items with their ratio

/*

for (int i = 0; i < n; i++)

cout << arr[i].value << " " << arr[i].weight << " : "
<< ((double)arr[i].value / arr[i].weight) << endl;

*/

int curWeight = 0; // Current weight in knapsack

double finalvalue = 0.0; // Result (value in Knapsack)

// Looping through all Items

for (int i = 0; i < n; i++)

// If adding Item won't overflow, add it completely

if (curWeight + arr[i].weight <= W)

curWeight += arr[i].weight;

finalvalue += arr[i].value;

// If we can't add current Item, add fractional part of it

else

int remain = W - curWeight;

finalvalue += arr[i].value * ((double) remain / arr[i].weight);

break;

// Returning final value

return finalvalue;

// driver program to test above function

int main()

int W = 50; // Weight of knapsack


Item arr[] = {{60, 10}, {100, 20}, {120, 30}};

int n = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum value we can obtain = "

<< fractionalKnapsack(W, arr, n) << endl;

return 0;

Output
Maximum value we can obtain = 240
BFS and DFS in Graph
#include<iostream>

#include <list>

using namespace std;

// This class represents a directed graph using

// adjacency list representation

class Graph

int V; // No. of vertices

// Pointer to an array containing adjacency

// lists

list<int> *adj;

void DFSUtil(int v, bool visited[]);

public:

Graph(int V); // Constructor

// function to add an edge to graph

void addEdge(int v, int w);

// prints BFS traversal from a given source s

void BFS(int s);

void DFS(int v);

};

Graph::Graph(int V)

this->V = V;

adj = new list<int>[V];


}

void Graph::addEdge(int v, int w)

adj[v].push_back(w); // Add w to v’s list.

void Graph::BFS(int s)

// Mark all the vertices as not visited

bool *visited = new bool[V];

for(int i = 0; i < V; i++)

visited[i] = false;

// Create a queue for BFS

list<int> queue;

// Mark the current node as visited and enqueue it

visited[s] = true;

queue.push_back(s);

// 'i' will be used to get all adjacent

// vertices of a vertex

list<int>::iterator i;

while(!queue.empty())

// Dequeue a vertex from queue and print it

s = queue.front();

cout << s << " ";

queue.pop_front();

// Get all adjacent vertices of the dequeued

// vertex s. If a adjacent has not been visited,

// then mark it visited and enqueue it

for (i = adj[s].begin(); i != adj[s].end(); ++i)


{

if (!visited[*i])

visited[*i] = true;

queue.push_back(*i);

cout << endl;

void Graph::DFSUtil(int v, bool visited[])

// Mark the current node as visited and

// print it

visited[v] = true;

cout << v << " ";

// Recur for all the vertices adjacent

// to this vertex

list<int>::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[*i])

DFSUtil(*i, visited);

// DFS traversal of the vertices reachable from v.

// It uses recursive DFSUtil()


void Graph::DFS(int v)

// Mark all the vertices as not visited

bool *visited = new bool[V];

for (int i = 0; i < V; i++)

visited[i] = false;

// Call the recursive helper function

// to print DFS traversal

DFSUtil(v, visited);

cout << endl;

// Driver program to test methods of graph class

int main()

// Create a graph given in the above diagram

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "

<< "(starting from vertex 2) \n";

g.BFS(2);
cout << "Following is Depth First Traversal"

" (starting from vertex 2) \n";

g.DFS(2);

return 0;

Output
Following is Breadth First Traversal (starting from vertex 2)

2031

Following is Depth First Traversal (starting from vertex 2)

2013

Floyd Warshall’s Algorithm


#include<stdio.h>

// Number of vertices in the graph

#define V 4

/* Define Infinite as a large enough value. This value will be used

for vertices not connected to each other */

#define INF 99999

// A function to print the solution matrix

void printSolution(int dist[][V]);

// Solves the all-pairs shortest path problem using Floyd Warshall algorithm

void floydWarshall (int graph[][V])

/* dist[][] will be the output matrix that will finally have the shortest

distances between every pair of vertices */

int dist[V][V], i, j, k;

/* Initialize the solution matrix same as input graph matrix. Or


we can say the initial values of shortest distances are based

on shortest paths considering no intermediate vertex. */

for (i = 0; i < V; i++)

for (j = 0; j < V; j++)

dist[i][j] = graph[i][j];

/* Add all vertices one by one to the set of intermediate vertices.

---> Before start of an iteration, we have shortest distances between all

pairs of vertices such that the shortest distances consider only the

vertices in set {0, 1, 2, .. k-1} as intermediate vertices.

----> After the end of an iteration, vertex no. k is added to the set of

intermediate vertices and the set becomes {0, 1, 2, .. k} */

for (k = 0; k < V; k++)

// Pick all vertices as source one by one

for (i = 0; i < V; i++)

// Pick all vertices as destination for the

// above picked source

for (j = 0; j < V; j++)

// If vertex k is on the shortest path from

// i to j, then update the value of dist[i][j]

if (dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

// Print the shortest distance matrix

printSolution(dist);
}

/* A utility function to print solution */

void printSolution(int dist[][V])

printf ("The following matrix shows the shortest distances"

" between every pair of vertices \n");

for (int i = 0; i < V; i++)

for (int j = 0; j < V; j++)

if (dist[i][j] == INF)

printf("%7s", "INF");

else

printf ("%7d", dist[i][j]);

printf("\n");

int main() {

int graph[V][V] = { {0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1},

{INF, INF, INF, 0}

};

// Print the solution

floydWarshall(graph);
return 0;

Output
The following matrix shows the shortest distances between every pair of vertices

0 5 8 9

INF 0 3 4

INF INF 0 1

INF INF INF 0


Bellman Ford Algorithm
#include <bits/stdc++.h>

// a structure to represent a weighted edge in graph

struct Edge

int src, dest, weight;

};

// a structure to represent a connected, directed and

// weighted graph

struct Graph

// V-> Number of vertices, E-> Number of edges

int V, E;

// graph is represented as an array of edges.

struct Edge* edge;

};

// Creates a graph with V vertices and E edges

struct Graph* createGraph(int V, int E)

struct Graph* graph = new Graph;

graph->V = V;

graph->E = E;

graph->edge = new Edge[E];

return graph;

}
// A utility function used to print the solution

void printArr(int dist[], int n)

printf("Vertex Distance from Source\n");

for (int i = 0; i < n; ++i)

printf("%d \t\t %d\n", i, dist[i]);

// The main function that finds shortest distances from src to

// all other vertices using Bellman-Ford algorithm. The function

// also detects negative weight cycle

void BellmanFord(struct Graph* graph, int src)

int V = graph->V;

int E = graph->E;

int dist[V];

// Step 1: Initialize distances from src to all other vertices

// as INFINITE

for (int i = 0; i < V; i++)

dist[i] = INT_MAX;

dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times. A simple shortest

// path from src to any other vertex can have at-most |V| - 1

// edges

for (int i = 1; i <= V-1; i++)

{
for (int j = 0; j < E; j++)

int u = graph->edge[j].src;

int v = graph->edge[j].dest;

int weight = graph->edge[j].weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v])

dist[v] = dist[u] + weight;

// Step 3: check for negative-weight cycles. The above step

// guarantees shortest distances if graph doesn't contain

// negative weight cycle. If we get a shorter path, then there

// is a cycle.

for (int i = 0; i < E; i++)

int u = graph->edge[i].src;

int v = graph->edge[i].dest;

int weight = graph->edge[i].weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v])

printf("Graph contains negative weight cycle");

printArr(dist, V);

return;

// Driver program to test above functions


int main()

/* Let us create the graph given in above example */

int V = 5; // Number of vertices in graph

int E = 8; // Number of edges in graph

struct Graph* graph = createGraph(V, E);

// add edge 0-1 (or A-B in above figure)

graph->edge[0].src = 0;

graph->edge[0].dest = 1;

graph->edge[0].weight = -1;

// add edge 0-2 (or A-C in above figure)

graph->edge[1].src = 0;

graph->edge[1].dest = 2;

graph->edge[1].weight = 4;

// add edge 1-2 (or B-C in above figure)

graph->edge[2].src = 1;

graph->edge[2].dest = 2;

graph->edge[2].weight = 3;

// add edge 1-3 (or B-D in above figure)

graph->edge[3].src = 1;

graph->edge[3].dest = 3;

graph->edge[3].weight = 2;

// add edge 1-4 (or A-E in above figure)

graph->edge[4].src = 1;
graph->edge[4].dest = 4;

graph->edge[4].weight = 2;

// add edge 3-2 (or D-C in above figure)

graph->edge[5].src = 3;

graph->edge[5].dest = 2;

graph->edge[5].weight = 5;

// add edge 3-1 (or D-B in above figure)

graph->edge[6].src = 3;

graph->edge[6].dest = 1;

graph->edge[6].weight = 1;

// add edge 4-3 (or E-D in above figure)

graph->edge[7].src = 4;

graph->edge[7].dest = 3;

graph->edge[7].weight = -3;

BellmanFord(graph, 0);

return 0;

Output
Vertex Distance from Source

0 0

1 -1

2 2

3 -2

4 1

Você também pode gostar