Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

find second largest number in array c++

/*
quick explaination
basicly its searching for the largest UNSIGNED INT in an array of UNSIGNED INT where all the elements are the same size in bytes but the size in all the elements is a variable and can be changed

this method is finding the largest number but to find the second or third or even sort the array
i will create some sort of stack where each element is pushed but sense this is to find the 2nd largest number
it will just do that but you get the idea if you want to change the code to be something that fits you

suggestion : if you already know what size of numbers your array will be then its better to create
an easier and much effecient method in your case but this is a general one where the size isn't really knowen
*/

int GetLargestUnsignedIntElement(void* array_ptr, int array_length, int var_size)
{
	void* var = malloc(var_size); 
	int second_largest = 0; //to be returned
	int largest_index = 0;
    //both the integers above are more like a "stack" but much more effecient
    //than using a real stack class
	bool Larger = false;
	for (int x = 0; x < var_size; x++) 
	{
		*(unsigned char*)((int)var + x) = 0;
	}
	for (int index = 0, ptr = (int)array_ptr; index < array_length; index++, ptr = ((int)array_ptr) + (index * var_size))
	{
		for (int i = 0, iptr = ptr; i < var_size; i++, iptr++)
		{
			if (*(unsigned char*)iptr > *(unsigned char*)((int)var + i))
			{
				Larger = true;
				continue; 
			}
			else if (*(unsigned char*)iptr == *(unsigned char*)((int)var + i))
			{
				continue; 
			}
			else
			{
				Larger = false; 
				continue;
			}
		}
		if (Larger)
		{
			for (int x = ptr, y = (int)var; x < (ptr + var_size); x++, y++)
			{
				*(unsigned char*)y = *(unsigned char*)x;
			}
          	//push the result
			second_largest = largest_index;
			largest_index = index;
          
		}
		else
		{
			continue;
		}
	}

	free(var);
	return second_largest;
}
Source by beginnersbook.com #
 
PREVIOUS NEXT
Tagged: #find #largest #number #array
ADD COMMENT
Topic
Name
2+9 =